Compare commits
No commits in common. "59f97236cdc4e7616f89f2edab2bcf34020978a8" and "50e48e7d0e50877ea57f574b4cccfe909a6fdce5" have entirely different histories.
59f97236cd
...
50e48e7d0e
@ -8,8 +8,6 @@ defmodule LiveViewCounter.Application do
|
||||
@impl true
|
||||
def start(_type, _args) do
|
||||
children = [
|
||||
# Start the App State
|
||||
LiveViewCounter.Count,
|
||||
# Start the Telemetry supervisor
|
||||
LiveViewCounterWeb.Telemetry,
|
||||
# Start the PubSub system
|
||||
|
||||
@ -1,55 +0,0 @@
|
||||
defmodule LiveViewCounter.Count do
|
||||
use GenServer
|
||||
|
||||
alias Phoenix.PubSub
|
||||
|
||||
@name :count_server
|
||||
|
||||
@start_value 0
|
||||
|
||||
# ------- External API (runs in client process) -------
|
||||
|
||||
def topic do
|
||||
"count"
|
||||
end
|
||||
|
||||
def start_link(_opts) do
|
||||
GenServer.start_link(__MODULE__, @start_value, name: @name)
|
||||
end
|
||||
|
||||
def incr() do
|
||||
GenServer.call @name, :incr
|
||||
end
|
||||
|
||||
def decr() do
|
||||
GenServer.call @name, :decr
|
||||
end
|
||||
|
||||
def current() do
|
||||
GenServer.call @name, :current
|
||||
end
|
||||
|
||||
def init(start_count) do
|
||||
{:ok, start_count}
|
||||
end
|
||||
|
||||
# ------- Implementation (Runs in GenServer process) -------
|
||||
|
||||
def handle_call(:current, _from, count) do
|
||||
{:reply, count, count}
|
||||
end
|
||||
|
||||
def handle_call(:incr, _from, count) do
|
||||
make_change(count, +1)
|
||||
end
|
||||
|
||||
def handle_call(:decr, _from, count) do
|
||||
make_change(count, -1)
|
||||
end
|
||||
|
||||
defp make_change(count, change) do
|
||||
new_count = count + change
|
||||
PubSub.broadcast(LiveViewCounter.PubSub, topic(), {:count, new_count})
|
||||
{:reply, new_count, new_count}
|
||||
end
|
||||
end
|
||||
@ -1,25 +1,16 @@
|
||||
defmodule LiveViewCounterWeb.Counter do
|
||||
use Phoenix.LiveView
|
||||
alias LiveViewCounter.Count
|
||||
alias Phoenix.PubSub
|
||||
|
||||
@topic Count.topic
|
||||
|
||||
def mount(_params, _session, socket) do
|
||||
PubSub.subscribe(LiveViewCounter.PubSub, @topic)
|
||||
{:ok, assign(socket, val: Count.current()) }
|
||||
{:ok, assign(socket, :val, 0)}
|
||||
end
|
||||
|
||||
def handle_event("inc", _, socket) do
|
||||
{:noreply, assign(socket, :val, Count.incr())}
|
||||
{:noreply, update(socket, :val, &(&1 + 1))}
|
||||
end
|
||||
|
||||
def handle_event("dec", _, socket) do
|
||||
{:noreply, assign(socket, :val, Count.decr())}
|
||||
end
|
||||
|
||||
def handle_info({:count, count}, socket) do
|
||||
{:noreply, assign(socket, val: count)}
|
||||
{:noreply, update(socket, :val, &(&1 - 1))}
|
||||
end
|
||||
|
||||
def render(assigns) do
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user