Are there elegant ways to sub/unsub when user navigated between routers in same liveview?

As far as I know, your intuition is right, implement conditional deregistration and registration as part of handle_params/3 (possibly extracted into a defp helper.)

If you don’t already, store the current product ID in an assign. You can assign it to nil on mount/3, so that in handle_params/3 you can easily distinguish if you just started and there’s no state to clean up, or if you navigated between products. Assign the current product ID in the handle_params/3 callback.

Don’t forget to check the current product ID in your handle_info/2 callback, and discard messages unrelated to the current product.

4 Likes