Skip to content

Commit

Permalink
broadcast count to all connected clients Step 13 #1
Browse files Browse the repository at this point in the history
  • Loading branch information
nelsonic committed Mar 9, 2020
1 parent e6dd077 commit 48c1c29
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 12 deletions.
19 changes: 10 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1038,21 +1038,12 @@ We can share the counter state
between multiple clients by updating the `counter.ex` file
with the following code:


TODO: Broadcast the Inc/Dec Signal!

https://github.com/dwyl/phoenix-liveview-counter-tutorial/blob/20bea0b36f0a6a054b4398c5f69fe4a1583282c4/lib/live_view_counter_web/live/counter_live.ex

```elixir
defmodule LiveViewCounterWeb.Counter do
use Phoenix.LiveView

@topic "live"

def render(assigns) do
LiveViewCounterWeb.PageView.render("counter.html", assigns)
end

def mount(_session, socket) do
LiveViewCounterWeb.Endpoint.subscribe(@topic)
{:ok, assign(socket, :val, 0)}
Expand All @@ -1073,6 +1064,16 @@ defmodule LiveViewCounterWeb.Counter do
def handle_info(msg, socket) do
{:noreply, assign(socket, msg.payload)}
end

def render(assigns) do
~L"""
<div>
<h1>The count is: <%= @val %></h1>
<button phx-click="dec">-</button>
<button phx-click="inc">+</button>
</div>
"""
end
end
```

Expand Down
17 changes: 14 additions & 3 deletions lib/live_view_counter_web/live/counter.ex
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
defmodule LiveViewCounterWeb.Counter do
use Phoenix.LiveView

def mount(_params, _session, socket) do
@topic "live"

def mount(_session, socket) do
LiveViewCounterWeb.Endpoint.subscribe(@topic) # subscribe to the channel
{:ok, assign(socket, :val, 0)}
end

def handle_event("inc", _, socket) do
{:noreply, update(socket, :val, &(&1 + 1))}
def handle_event("inc", _value, socket) do
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
new_state = update(socket, :val, &(&1 - 1))
LiveViewCounterWeb.Endpoint.broadcast_from(self(), @topic, "dec", new_state.assigns)
{:noreply, update(socket, :val, &(&1 - 1))}
end

def handle_info(msg, socket) do
{:noreply, assign(socket, msg.payload)}
end

def render(assigns) do
~L"""
<div>
Expand Down

0 comments on commit 48c1c29

Please sign in to comment.