Search code examples
javascriptjquerychatpubnubunsubscribe

Pubnub - unsubscribe all active users from a specific channel


Does anyone know if there's a Pubnub function to unsubscribe all the users from a channel at once? And I mean without manipulating the regular function

pubnub.unsubscribe({
channel: 'my_channel',
callback: function() {
/* something */
}
});

I started building a function for mass unsubscribing myself - but hey, it's always a good idea to ask around before trying something obnoxious!

p.s - sorry if this Pubnub question has been asked before. I looked around and it seemed unanswered.

Thanks!


Solution

  • PubNub Unsubscribe All Users from a Specific Channel

    Use a control channel to specify which channels all users should subscribe to.

    // Subscribe to 'control' channel
    pubnub.subscribe({
        channel : 'control',
        message : function(command) {
            // Unsubscribe Command
            if (command.type == 'unsubscribe')
                return pubnub.unsubscribe({
                    channel : command.channel
                });
        }
    })
    
    // Subscribe to other channels
    pubnub.subscribe({
        channel : 'ch1,ch2',
        message : function(msg) { console.log(msg) }
    })
    

    This will signal all users listening on the control channel to unsubscribe from a specific channel name. This works pretty well out of the box. And the signal you would send to unsubscribe will look like this:

    pubnub.publish({
        channel : 'control',
        message : {
            command : 'unsubscribe',
            channel : 'channel_to_unsubscribe'
        }
    })