Listening for Events

As soon as you call watch on a Channel or queryChannels you’ll start to listen to these events. You can hook into specific events:

channel.on("message.deleted", (event) => {
  console.log("event", event);
  console.log("channel.state", channel.state);
});

You can also listen to all events at once: (Full list of events is on events object page)

channel.on((event) => {
  console.log("event", event);
  console.log("channel.state", channel.state);
});

Client Events

Not all events are specific to channels. Events such as the user’s status has changed, the users’ unread count has changed, and other notifications are sent as client events. These events can be listened to through the client directly:

// subscribe to all client events and log the unread_count field
client.on((event) => {
  if (event.total_unread_count !== null) {
    console.log(`unread messages count is now: ${event.total_unread_count}`);
  }

  if (event.unread_channels !== null) {
    console.log(`unread channels count is now: ${event.unread_channels}`);
  }
});

// the initial count of unread messages is returned by client.connectUser
const user = await client.connectUser(user, userToken);
console.log(
  `you have ${user.me.total_unread_count} unread messages on ${user.me.unread_channels} channels.`,
);

Connection Events

The official SDKs make sure that a connection to Stream is kept alive at all times and that chat state is recovered when the user’s internet connection comes back online. Your application can subscribe to changes to the connection using client events.

client.on("connection.changed", (e) => {
  if (e.online) {
    console.log("the connection is up!");
  } else {
    console.log("the connection is down!");
  }
});

Stop Listening for Events

It is a good practice to unregister event handlers once they are not in use anymore. Doing so will save you from performance degradations coming from memory leaks or even from errors and exceptions (i.e. null pointer exceptions)

// remove the handler from all client events
// const myClientEventListener = client.on('connection.changed', myClientEventHandler)
myClientEventListener.unsubscribe();

// remove the handler from all events on a channel
// const myChannelEventListener = channel.on('connection.changed', myChannelEventHandler)
myChannelEventListener.unsubscribe();
© Getstream.io, Inc. All Rights Reserved.