oliverandrich

oliverandrich

How to implement PubSub with LiveView?

Hi,

I still working through this article and have now reached the phase, where I want to implement the immediate disconnecting of LiveViews on logout.

Sadly, I seem to misunderstand something or did something, so it doesn’t work. In the end, my problem is, that I think that the LiveViews are connected to a PubSub channel on mount. To do so I call in my mount function:

Jocasta.Endpoint.subscribe(@my_pubsub_topic)

I also added a plain handle_info function to my LiveViews, that should just dump out the message for me.

@impl true
def handle_info(msg, socket) do
  IO.inspect(msg)
  {:noreply, socket}
end

Then I broadcast a message somewhere else.

Jocasta.Endpoint.broadcast_from(
     self(),
     UserAuth.pubsub_topic(),
     "logout_user",
     %{
       user: user
     }
   )

Somehow my message never ends up in my handle_info method or better said, this method is never called.

Being rather new to Phoenix, I have some stupid quesions.

  • Can I find out which subscribers exist for a given topic?
  • Is the assumption correct that subscribe and broadcast belong to the PubSub system?
  • Do I totally misunderstand here something?

I thought I replicated everything the author does in his repo. Sadly, I seem to miss something and started to strip his example to the absolute basics of sending and receiving messages via PubSub.

Any help is appreciated.

Best regards
Oliver

Marked As Solved

LostKobrakai

LostKobrakai

May I ask why you’re using pubsub manually over this:

Also Liked

50kudos

50kudos

Can I find out which subscribers exist for a given topic?

Registry.lookup(Jocasta.PubSub, topic) the result can contain metadata passed to when calling subscribe (e.g. Phoenix.PubSub.subscribe(Jocasta.PubSub, topic, metadata: %{ip: ip}))

Is the assumption correct that subscribe and broadcast belong to the PubSub system?

It belongs to pubsub_server configured here

config :fset, JocastaWeb.Endpoint,
  ...
  pubsub_server: Jocasta.PubSub,
  live_view: [signing_salt: "abc"]

And that PubSub is usually (or by default, not sure since which phoenix version) started in root supervision tree.

Do I totally misunderstand here something?

Not sure! If that broadcast_from works, you would want to test it in a separate node to see if it actually works. Or use local_broadcast_from.

slouchpie

slouchpie

I have been following this same article and had some concerns about the proposed use of PubSub. The link posted above by @LostKobrakai is a much better approach.

I want to mention this:
I used phx_gen_auth in my project and that generated this line in the log_in_user function:

conn
# ...
|> put_session(:live_socket_id, "users_sessions:#{Base.url_encode64(token)}")

So for anyone else like me, you can keep this line and log users out like this:

  @doc """
  Logs a user out of any and all sessions
  """
  def force_logout_user(%User{id: user_id} = user) do
    user_tokens = UserToken
    |> where(user_id: ^user_id)
    |> Repo.all()

    Repo.delete_all(UserToken.user_and_contexts_query(user, :all))

    user_tokens
    |> Enum.each(fn %UserToken{token: token} ->
      MyAppWeb.Endpoint.broadcast(
        "users_sessions:#{Base.url_encode64(token)}",
        "disconnect",
        %{}
      )
    end)
  end

Just make sure you change mount functions in any live views you have that might assume a current_user on the assigns.

oliverandrich

oliverandrich

Because I didn’t knew about this. This is really helpful. Thanks for pointing this out to me.

Last Post!

slouchpie

slouchpie

When I call force_logout_user the logged in user’s browser navigates to the login page.

Are you definitely putting the live socket ID on the sesssion? I have something like this in my log_in function:

    |> put_session(:live_socket_id, "users_sessions:#{Base.url_encode64(token)}")

and that token is stored in the database.

Take a look at the Network tab in your devtools to investigate the problem.

Where Next?

Popular in Questions Top

electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

Other popular topics Top

grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 54260 488
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 44265 214
New

We're in Beta

About us Mission Statement