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.

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New

Other popular topics Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
New
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
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
AstonJ
Please see the new poll here: Which code editor or IDE do you use? (Poll) (2022 Edition) It’s been a while since we first asked this, I...
208 31142 143
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

We're in Beta

About us Mission Statement