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

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
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
vac
Hi, I’m quite new in Elixir and I’m trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and I...
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: <h1>Create Post</h1> <%= ...
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
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
New
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36128 110
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement