Skip to content Skip to sidebar Skip to footer

"existing Subscription To Channel" While Only Subscribing Once

I have a small snippet that throws an 'Existing subscription to channel' exception even though I only call the subscribe method once. This can be avoided by moving the subscribe re

Solution 1:

While it does look like a bug in the library (do report it!), you don't need to bind to the state_change event in order to subscribe to channels.

If you look at the code for the subscribe event in pusher.js:

prototype.subscribe = function(channel_name) {
  var self = this;
  var channel = this.channels.add(channel_name, this);

  if (this.connection.state === 'connected') {
    channel.authorize(this.connection.socket_id, function(err, data) {
      if (err) {
        channel.handleEvent('pusher:subscription_error', data);
      } else {
        self.send_event('pusher:subscribe', {
          channel: channel_name,
          auth: data.auth,
          channel_data: data.channel_data
        });
      }
    });
  }
  return channel;
};

you'll see that it will first add your channel to an internal list of channels via the channels.add method, which looks like this:

prototype.add = function(name, pusher) {
  if (!this.channels[name]) {
    this.channels[name] = createChannel(name, pusher);
  }
  returnthis.channels[name];
};

It will only add the channel in case you haven't previously subscribed.

So, if you were to subscribe to a channel before the connection is established, the Pusher client will only add the channel to the list. Once the client has established a connection, it will call the subscribe method again for every channel in its list via the subscribeAll method:

this.connection.bind('connected', function() {
  self.subscribeAll();
});

And seeing that at this point this.connection.stateisconnected, it will connect.

So, recapping, don't bother binding to the state_change event to subscribe, just subscribe, like so:

<!doctype html><html><body><h1>Pusher subscribe testcase</h1><p>Tip: check your console</p><scriptsrc="https://d3dy5gmtp8yhk7.cloudfront.net/2.1/pusher.js"></script><script>var pusher, channel;

        pusher = newPusher('XXXXXXXXXXXXXXXX');
        channel = pusher.subscribe('test-channel');
        channel.bind('pusher:subscription_succeeded', function() {
            console.log('subscribed');
        });
    </script></body></html>

Solution 2:

It looks like a bug. If you open up the Network tab in dev tools and look at the WebSocket connection "Frames" information you can see the pusher:subscribe protocol event being sent twice. However, the code is definitely only calling pusher.subscribe once.

You should raise this bug with Pusher support or by submitting an issue to the github repo.

pusher:subscribe protocol event sent twice

Post a Comment for ""existing Subscription To Channel" While Only Subscribing Once"