Listening for Events

Last Edit: Mar 03 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
                    

channel.onEvent(.messageNew)
    .subscribe(onNext: { event in
        print(event)
    })
    .disposed(by: disposeBag)
                    

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

channel.onEvent()
    .subscribe(onNext: { event in
        print(event)
    })
    .disposed(by: disposeBag)
                    

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.
Client.shared.onEvent(.userPresenceChanged)
    .subscribe(onNext: { event in
        print(event)
    })
    .disposed(by: disposeBag)

// Unread count globally.
Client.shared.unreadCount
    .subscribe(onNext: { unreadCount in
        print(unreadCount)
    })
    .disposed(by: disposeBag)

// Unread count for a channel.
channel.unreadCount
    .subscribe(onNext: { unreadCount in
        print(unreadCount)
    })
    .disposed(by: disposeBag)
                    

// 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.
Client.shared.connection
    .subscribe(onNext: { connection in
        print(connection)
    })
    .disposed(by: disposeBag)

// Get an event when only the client is connected.
Client.shared.connection.connected()
    .subscribe(onNext: {
        print("You are online")
    })
    .disposed(by: disposeBag)
                    

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

// TODO
                    

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.off(myClientEventHandler);

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

// remove the handler for all "message.new" events on the channel
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);
                    

channel.stopWatching().subscribe().disposed(by: disposeBag)
                    

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