I'm using Phoenix channels to stream data to a page with a tabbed interface. I'd like to only receive messages from a channel when the streaming tab is visible and to disconnect from the channel when the user has switched to another tab.
Currently I use something similar to the following code:
window.websockets_url = "ws://localhost:4000/socket";
window.channel_id = "some-channel-id"
onWindowLoad = ->
initSocket()
onStreamShow = ->
connectToSocket()
onStreamHide = ->
disconnectFromSocket()
initSocket = ->
window.socket = new (Phoenix.Socket)(window.websockets_url)
connectToSocket = ->
window.socket.connect()
channel = window.socket.channel("channel:#{window.channel_id}", {})
channel.join()
channel.on "event", (payload) ->
doSomethingWithThePayload(payload)
disconnectFromSocket = ->
window.socket.disconnect()
This works, but after calling connectToSocket()
and disconnectFromSocket()
multiple times I'm getting this message in the server logs:
StreamChannel received join event with topic "channel:some-channel-id" but channel already joined
How can I avoid this?
The Phoenix Socket API in Javascript is stateful. When you reconnect after a disconnect, it will reconnect to all the previous channels. You're then joining the channel a second time.
You can either re-initialize the socket (initSocket) or only join channels on the first connect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With