Is there a way to check if a LiveView socket is currently navigating?

Hey yall,

I’m working on a hook where I would like some certain behavior to happen if the socket is currently in the middle of a live_navigate. Is there something I can look at on the socket to know that a navigation is in progress?

The basic situation is I have a toast library, and a function called put_toast that works by doing a send_update to a LC on the page. But in order to make it work across live navigations, I want to detect that a navigation is in progress and push a broadcast into a pubsub topic to be pulled out after the navigation is done. If anyone has a better idea on how to accomplish that let me know.

I’m not sure I fully understand what you’re trying to accomplish. The push_redirect function literally just annotates the socket with a flag to redirect. I don’t know enough about the LiveView interals to know how long this annotation stays on the socket, but you could try playing with it. If you control the redirect you could also store a flag in the assigns yourself.

More generally though, my gut reaction is that what you’re trying to do is probably a bad idea. I don’t understand what you mean by “push a broadcast into a pubsub topic to be pulled out” - Phoenix PubSub is essentially just fanout for message passing as I understand it. The successor LiveView won’t receive the message unless it subscribes before the first LiveView sends it (for some definition of “before”, anyway), so I would expect this use case to be drenched in race conditions.

If you actually need persistent storage that outlives an individual LiveView, you could use a database, or put together a simple GenServer that stores the state (maybe in ets). You could also potentially store the state on the client if that’s appropriate.

Finally, you could mount a separate LiveView (not a component) on the same page to store the toasts. I have never actually run multiple LiveViews but you can apparently do it with live_render/3.