Skip to content
Permalink
Browse files

updating in real-time with pubsub

  • Loading branch information...
dnsbty committed Apr 13, 2019
1 parent b8535b7 commit 48c5dfe528ed704cd798334b48177d351a906cff
Showing with 22 additions and 1 deletion.
  1. +16 −1 lib/live_view_todos/todos.ex
  2. +6 −0 lib/live_view_todos_web/live/todo_live.ex
@@ -7,6 +7,11 @@ defmodule LiveViewTodos.Todos do
alias LiveViewTodos.Repo

alias LiveViewTodos.Todos.Todo
@topic inspect(__MODULE__)

def subscribe do
Phoenix.PubSub.subscribe(LiveViewTodos.PubSub, @topic)
end

@doc """
Returns the list of todos.
@@ -53,6 +58,7 @@ defmodule LiveViewTodos.Todos do
%Todo{}
|> Todo.changeset(attrs)
|> Repo.insert()
|> broadcast_change([:todo, :created])
end

@doc """
@@ -71,6 +77,7 @@ defmodule LiveViewTodos.Todos do
todo
|> Todo.changeset(attrs)
|> Repo.update()
|> broadcast_change([:todo, :updated])
end

@doc """
@@ -86,7 +93,9 @@ defmodule LiveViewTodos.Todos do
"""
def delete_todo(%Todo{} = todo) do
Repo.delete(todo)
todo
|> Repo.delete()
|> broadcast_change([:todo, :deleted])
end

@doc """
@@ -101,4 +110,10 @@ defmodule LiveViewTodos.Todos do
def change_todo(%Todo{} = todo) do
Todo.changeset(todo, %{})
end

defp broadcast_change({:ok, result}, event) do
Phoenix.PubSub.broadcast(LiveViewTodos.PubSub, @topic, {__MODULE__, event, result})

{:ok, result}
end
end
@@ -5,6 +5,8 @@ defmodule LiveViewTodosWeb.TodoLive do
alias LiveViewTodosWeb.TodoView

def mount(_session, socket) do
Todos.subscribe()

{:ok, fetch(socket)}
end

@@ -18,6 +20,10 @@ defmodule LiveViewTodosWeb.TodoLive do
{:noreply, fetch(socket)}
end

def handle_info({Todos, [:todo | _], _}, socket) do
{:noreply, fetch(socket)}
end

defp fetch(socket) do
assign(socket, %{todos: Todos.list_todos()})
end

0 comments on commit 48c5dfe

Please sign in to comment.
You can’t perform that action at this time.