JS client: subscriptions and component lifecycle
How to subscribe and clean up with the IO client in the browser and Node.js. The flow shared by every environment (what ready means, what happens to the CID and subscriptions after a reconnection) is in connection and CID lifecycle, and every method and event is in the client API.
Connection state names
ready means the client has a CID and can communicate. It differs from the socket's open state and fires again after every reconnection. The change event reports these state names.
Handling reconnection
ready is not a one-time event for the first connection. When the connection drops and the library reconnects, it receives a CID again and ready fires again. Reset application state to match that lifecycle.
let currentCid = null;
io.on('ready', () => {
currentCid = io.cid; // Refresh on every reconnection.
io.subscribe('room#chat'); // Re-register manual subscriptions.
rebuildRoomState(currentCid); // Rebuild peer and room state.
});
io.listen('alarm#state', (tag, ...args) => {
console.log(tag, ...args);
}); // Normal tags are re-subscribed automatically.
io.on('change', (state) => {
if (state === 'closed') currentCid = null;
});
- CID changes: A closed connection clears the client
cid, and the next connection may receive a different one. This is especially true for anonymous connections. Rebuild peer lists, permissions, and room state that were keyed by the old CID on the nextready. - Manual subscriptions:
subscribe()applies only to the current connection and does not survive reconnection. Register it again in everyreadyhandler. - Automatic subscriptions: For normal tags registered with
listen(), the library subscribes again on reconnection from the.channelslist. Direct reception (@,@topic) needs no subscription. - Application function:
rebuildRoomState()in the example is an application function, not a library API. - Redirects and disconnects: A public server may redirect the first connection or a login to another server. That is a normal pre-
readystep, not the same as an unexpected disconnect after readiness. Do not treat them as one error, and bound the connection wait. - Server reply limit (from 9.19.0): if the server's first reply does not arrive within 15 seconds of starting a connection, the client emits
errorand closes the connection. With auto-reconnect it connects to the address it was created with, so it comes back to the original server when a redirected server cannot be reached. The Arduino library does the same with 10 seconds. - Cleanup: Call
stop()to end reconnection, ordestroy()to discard the instance. For a shared instance, useunlinkAll(component)to release that component'slink()registrations. It removes handlers registered throughlink()for that component and subscriptions owned only by those links; handlers registered withon()orlisten()are not removed.
Manual or automatic subscriptions
| Style | Best for | On connection/reconnection |
|---|---|---|
subscribe() + on() | Connection-state handling and subscriptions that change at run time | App subscribes in each ready handler |
listen(tag, handler) | Declaring known tags during initialization | Library subscribes using its saved .channels list |
Manual: subscribe before sending
const io = new IO();
const tag = 'channel1';
io.on('message', (receivedTag, ...args) => {
console.log(receivedTag, ...args);
});
io.on('ready', () => {
io.subscribe(tag);
io.signal(tag, io.cid + ' is ready.');
});
io.open('ws://localhost:7777');
Register the handler once and subscribe on each ready. subscribe(tag) does not accept a handler and does not itself add the tag to the automatic .channels list.
Call subscribe() only while the connection is ready. From 9.6.0 it throws an Error in any other state (before connecting, before the CID arrives, or while disconnected), because such a request would go out before authentication or be lost. After destroy() it does nothing.
Automatic: declare a tag and handler
const io = new IO();
io.listen('channel1', (tag, ...args) => {
console.log(tag, ...args);
});
io.open('ws://localhost:7777');
For ordinary tags, listen() saves the tag and registers the handler. The library subscribes after obtaining a CID, and resubscribes after reconnecting.
Register in setup code, before the first ready. Calling listen() does not immediately send a subscription packet. From 9.6.0, saved subscriptions are sent before the ready event, so a ready handler may call signal() at once without getting ahead of its own subscriptions.
Calling listen() inside a ready handler throws an Error, for any tag: a subscription tag registered there would be subscribed only after the next reconnection, and the handler would be registered again on every connection. In a ready handler use on() and subscribe(); for dynamic subscriptions while already ready, use subscribe() or link().
unsubscribe(tag) removes the server subscription and its saved tag. Direct listeners use on() or listen() with @/@topic, require no subscription, and can be registered any time before the message arrives. Remove a direct listener with off('@topic', handler). Direct subscribe()/unsubscribe() calls throw TypeError, including comma lists containing a direct tag. A@topic remains a valid CID-publication subscription.
Component ownership
link(component, tag, handler) takes a local component identifier, not a server address or recipient CID. Remove linked handlers with unlink(component, tag) or unlinkAll(component). Other components using the same function or tag keep their handlers.
io.link('offer-panel', '@offer', (tag, message) => {
console.log(tag, message);
});
// When the component is removed:
io.unlinkAll('offer-panel');
Direct @/@topic links only manage local listeners. Ordinary channel and CID-publication links also manage subscriptions and reconnection subscriptions: on a ready connection they subscribe at once, otherwise when the connection becomes ready.
Unlinking one component does not unsubscribe a tag still owned by another link, a listen() registration, or an explicit subscription. Removing the last link releases a subscription owned only by links. Explicit subscribe() ownership belongs to the current connection; automatic reconnection follows saved listen/link registrations.
Destroy an IO instance only when the departing component owns it exclusively.