websocketreal-timepublish-subscribeably-realtime

Can I attach and subscribe to channels using wildcards?


When using Ably for Pub/Sub over WebSockets, can I use wildcards to subscribe to multiple channels like so

var channel = ably.channels.get('foo:*') 
channel.attach()

(disclaimer: I am a developer advocate for Ably, and posting and self-answering a commonly asked support question here on Stack Overflow so our users can find this more easily)


Solution

  • When attaching to a channel, you need to explicitly provide the channel name you are attaching to such as:

    var channel = ably.channels.get('announcements')
    channel.attach()
    

    Attaching to more than one channel in a single operation is not possible, i.e. the following is not supported:

    var channel = ably.channels.get('foo:*') 
    channel.attach()
    /* attempting to attach to all channels matching the name foo:* will not work */
    

    This is not possible for a number of reasons:

    However, because Ably's connections are multiplexed thus allowing you to attach and detach from any channels dynamically over the same connection, it is of course possible to effectively subscribe to wildcard channels by attaching to channels as you need them.