From 87e5e79c04c9d4c45bb9c73c24739823e5098223 Mon Sep 17 00:00:00 2001 From: Peter Hart Date: Sun, 28 Aug 2022 13:07:20 -0400 Subject: [PATCH] initial shared counter state, with flaw that each new windows resets counter to 0... --- lib/live_view_counter_web/live/counter.ex | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/lib/live_view_counter_web/live/counter.ex b/lib/live_view_counter_web/live/counter.ex index 339e7e3..6fe8d3f 100644 --- a/lib/live_view_counter_web/live/counter.ex +++ b/lib/live_view_counter_web/live/counter.ex @@ -1,16 +1,27 @@ defmodule LiveViewCounterWeb.Counter do use Phoenix.LiveView + @topic "live" + def mount(_params, _session, socket) do + LiveViewCounterWeb.Endpoint.subscribe(@topic) {:ok, assign(socket, :val, 0)} end def handle_event("inc", _, socket) do - {:noreply, update(socket, :val, &(&1 + 1))} + new_state = update(socket, :val, &(&1 + 1)) + LiveViewCounterWeb.Endpoint.broadcast_from(self(), @topic, "inc", new_state.assigns) + {:noreply, new_state} end def handle_event("dec", _, socket) do - {:noreply, update(socket, :val, &(&1 - 1))} + new_state = update(socket, :val, &(&1 - 1)) + LiveViewCounterWeb.Endpoint.broadcast_from(self(), @topic, "dec", new_state.assigns) + {:noreply, new_state} + end + + def handle_info(msg, socket) do + {:noreply, assign(socket, val: msg.payload.val)} end def render(assigns) do