Skip to content
Permalink
Browse files

Make it Work in Real-Time

  • Loading branch information...
dnsbty committed Aug 18, 2019
1 parent 12fc141 commit 7b184d092138296398a64424bcb49d30969a2fc7
Showing with 24 additions and 0 deletions.
  1. +18 −0 lib/user_admin/users.ex
  2. +6 −0 lib/user_admin_web/live/user_live/index.ex
@@ -3,6 +3,8 @@ defmodule UserAdmin.Users do
alias UserAdmin.Repo
alias UserAdmin.Users.{Role, User}

@topic inspect(__MODULE__)

@doc """
Create a changeset to change a user.
"""
@@ -19,6 +21,7 @@ defmodule UserAdmin.Users do
%User{}
|> User.changeset(attrs)
|> Repo.insert()
|> broadcast_change([:user, :created])
end

@doc """
@@ -39,4 +42,19 @@ defmodule UserAdmin.Users do
|> preload([_, r], role: r)
|> Repo.all()
end

@doc """
Subscribe to updates to the user list.
"""
@spec subscribe :: :ok | {:error, term()}
def subscribe do
Phoenix.PubSub.subscribe(UserAdmin.PubSub, @topic)
end

@spec broadcast_change({:ok, User.t()}, list(atom())) :: :ok | {:error, term()}
defp broadcast_change({:ok, result}, event) do
Phoenix.PubSub.broadcast(UserAdmin.PubSub, @topic, {__MODULE__, event, result})

{:ok, result}
end
end
@@ -4,6 +4,7 @@ defmodule UserAdminWeb.UserLive.Index do
alias UserAdminWeb.UserView

def mount(_session, socket) do
Users.subscribe()
users = Users.list_users()

{:ok, assign(socket, :users, users)}
@@ -12,4 +13,9 @@ defmodule UserAdminWeb.UserLive.Index do
def render(assigns) do
UserView.render("index.html", assigns)
end

def handle_info({Users, [:user | _], _}, socket) do
users = Users.list_users()
{:noreply, assign(socket, users: users)}
end
end

0 comments on commit 7b184d0

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