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?