Listening for Events

Last Edit: Sep 22 2020

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);
});
                    

Integer channelSubscriptionId = channel.addEventHandler(new ChatChannelEventHandler() {
  @Override
  public void onMessageNew(Event event) {
      event.getMessage();
  }
}
// channel.removeEventHandler(channelSubscriptionId) to remove it
                    

let channel = Client.shared.channel(type: .messaging, id: "general")

let subscription = channel.subscribe(forEvents: [.messageNew]) { event in
	// handle new message event
}

// Cancel subscription when you want to stop receiving events
subscription.cancel()
                    

val subscription = channelController
    .events()
    .filter("message.deleted")
    .subscribe { messageDeletedEvent ->

    }
subscription.unsubscribe()
                    

channel.on("message.deleted").listen((Event event) {
  print("message ${event.message.id} was deleted");
});
                    

You can also listen to all events at once:


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

Integer channelSubscriptionId = channel.addEventHandler(new ChatChannelEventHandler() {
  @Override
  public void onAnyEvent(Event event) {
      event.getType();
  }
}
                    

let channel = Client.shared.channel(type: .messaging, id: "general")

let subscription = channel.subscribe { event in
	// handle new event
}

// Cancel subscription when you want to stop receiving events
subscription.cancel()
                    

val subscription = channelController.events().subscribe { event ->
    if (event is NewMessageEvent) {

    }
}
subscription.unsubscribe()
                    

channel.on().listen((Event event) {
  print("received a new event of type ${event.type}");
});
                    

Client Events

Not all events are specific to channels, events such as user status has changed, users' unread count has changed, and other notifications are sent as client events. These events should be registered on 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.setUser
const user = await client.setUser(user, userToken);
console.log(`you have ${user.me.total_unread_count} unread messages on ${user.me.unread_channels} channels.`);
                    

// receive an event whenever any of the channels that you are watching changes
Integer subscriptionId = client.addEventHandler(new ChatEventHandler() {
    @Override
    public void onMessageNew(Channel channel, Event event) {
        event.getMessage();
    }
});
                    

// Subscribe for user presence events.
let subscription = Client.shared.subscribe(forEvents: [.userPresenceChanged]) { event in
    // handle user presence changed event
}
// Cancel subscription when you want to stop receiving events
subscription.cancel()

// Unread count globally.
let subscription = Client.shared.subscribeToUnreadCount { count in
    // handle new unread count
}
// Cancel subscription when you want to stop receiving events
subscription.cancel()

// Unread count for a channel.
let channel = Client.shared.channel(type: .messaging, id: "general")
let subscription = channel.subscribeToUnreadCount { count in
    // handle new unread count
}
// Cancel subscription when you want to stop receiving events
subscription.cancel()
                    

// subscribe to all client events and log the unread_count field
client.events().subscribe { event ->
    if (event.totalUnreadCount != null) {
        println("unread messages count is now: ${event.totalUnreadCount}");
    }
    if (event.unreadChannels != null) {
        println("unread channels count is now: ${event.unreadChannels}");
    }

    if (event is ConnectedEvent) {
        // the initial count of unread messages is returned by client.setUser
        val unreadCount = event.user!!.totalUnreadCount
        val unreadChannels = event.user!!.unreadChannels
    }
}
                    

// subscribe to all client events and log the unread_count field
client.on().listen((event) => {
	if (event.totalUnreadCount != null) {
		print('unread messages count is now: ${event.totalUnreadCount}');
	}
 
	if (event.unreadChannels !== null) {
		print('unread channels count is now: ${event.unreadChannels}');
	}
});

// the initial count of unread messages is returned by client.setUser
final user = await client.setUser(user, userToken);
console.log(`you have ${user.me.totalUnreadCount} unread messages on ${user.me.unreadChannels} 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!');
    }
});
                    

Integer subscriptionId = client.addEventHandler(new ChatEventHandler() {
    @Override
    public void onConnectionChanged(Event event) {
        event.getOnline();
    }
});
                    

// Get all connection states.
let subscription = Client.shared.subscribe(forEvents: [.connectionChanged]) { event in
    // handle new connection state event
}
// Cancel subscription when you want to stop receiving events
subscription.cancel()
                    

client.events().subscribe { event ->
    when (event) {
        is ConnectedEvent -> {
            //socket is connected
        }
        is ConnectingEvent -> {
            //socket is connecting
        }
        is DisconnectedEvent -> {
            //socket is disconnected
        }
    }
}
                    

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

Stop Listening for Events

It is a good practice to de-register 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
// client.on('connection.changed', myClientEventHandler)
client.off(myClientEventHandler);

// remove the handler from all events on a channel
// channel.on('connection.changed', myChannelEventHandler)
channel.off(myChannelEventHandler);

// remove the handler for all "message.new" events on the channel
// channel.on('message.new', myChannelEventHandler)
channel.off("message.new", myChannelEventHandler);
                    

// remove the event handler based on the subscription ID returned by `client.addEventHandler`
client.removeEventHandler(subscriptionId);

// remove the event handler based on the subscription ID returned by `channel.addEventHandler`
channel.removeEventHandler(subscriptionId);
                    

// Get all connection states.
let subscription = Client.shared.subscribe(forEvents: [.connectionChanged]) { event in
    // handle new connection state event
}
// Cancel subscription when you want to stop receiving events
subscription.cancel()

// For subscriptions created via a channel, subscription is cancelled when channel is deallocated
                    

val subscription = channelController.events().subscribe { event -> }
subscription.unsubscribe()
                    

final subscription = channel.on().listen((Event event) {
  print("received a new event of type ${event.type}");
});

subscription.cancel();