From f5c35de8d8a44640fc5936b6be9e22adfed2f3cd Mon Sep 17 00:00:00 2001 From: Dan Barber Date: Tue, 13 Jul 2021 19:28:19 -0500 Subject: [PATCH] Clients subscribe to the game to get updates --- lib/chess_web/views/live/board_live.ex | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/lib/chess_web/views/live/board_live.ex b/lib/chess_web/views/live/board_live.ex index 1c122e7..ad8f03f 100644 --- a/lib/chess_web/views/live/board_live.ex +++ b/lib/chess_web/views/live/board_live.ex @@ -14,6 +14,8 @@ defmodule ChessWeb.BoardLive do end def mount(_params, %{"user_id" => user_id, "game_id" => game_id}, socket) do + ChessWeb.Endpoint.subscribe("game:#{game_id}") + user = Repo.get!(User, user_id) game = @@ -40,6 +42,10 @@ defmodule ChessWeb.BoardLive do } end + def handle_info(%{event: "move", payload: state}, socket) do + {:noreply, assign(socket, state)} + end + defp handle_click(socket, file, rank) do game = socket.assigns[:game] board = game.board @@ -87,6 +93,8 @@ defmodule ChessWeb.BoardLive do {:ok, %{game: game}} -> board = Board.transform(game.board) + broadcast_move(game, board) + [ {:selected, nil}, {:available, []}, @@ -98,4 +106,13 @@ defmodule ChessWeb.BoardLive do [{:selected, nil}, {:available, []}] end end + + defp broadcast_move(game, board) do + ChessWeb.Endpoint.broadcast_from( + self(), + "game:#{game.id}", + "move", + %{game: game, board: board} + ) + end end