Do I need to subscribe individually to each live view that accesses a value from a channel, even if they are all within the same layout?

I am using PubSub to list number of users that are in the database on the sidebar .
The sidebar is in a layout file as such .

<div>
  <.sidebar
    number_of_users={@number_of_users}
  />
  <main >
    <.flash_group flash={@flash} />
    <%= @inner_content %>
  </main>
</div>
  

I have an on_mount callback that adds the default value of number_of_users as the users in the database.
If this layout is used across multiple liveviews do I have to

  1. Subscribe to that topic on each liveview
  2. Call handle_info on each liveview to get the updated value of the users.

Currently, that is what I have gone with( subscribing to the topic on each liveview and calling handle_info on each liveview)

Thanks! :smiley:

1 Like

You can def solve it the way you done already. An alternative is to make a sticky liveview of the sidebar.

The benefits with that would be that you don’t need to fetch the data from the db every time you mount a new liveview (if you for example navigate across liveview sessions) and that you only need to subscribe to the topic in one liveview (the sidebar-liveview). Downside is that it can be a bit overkill (I don’t have a benchmark but I guess having sticky LiveViews have a server cost) and make things more complex (for example if you wanna show the current page option you might have to write some extra js to update that).

Good overview of it: Keep LiveViews alive across live redirects · The Phoenix Files

I would probably stick to your solution if it is only number_of_users in database that needs to be tracked in the sidebar. Sticky liveview is more “worth” it if you for example track 5 different stuff (for example notifications, new messages, new friend requests, etc) in my opinion.

1 Like

You could use a hook that can both subscribe to a topic and also attach some lifecycle callbacks (handle_info,handle_event etc) which can clean things up a bit.

https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#attach_hook/4

3 Likes

And don’t forget to check if the socket is connected before subscribing to topics.