Listening for Events

Last Edit: Nov 27 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);
});
                    

Disposable disposable = client.subscribeForSingle(NewMessageEvent.class,
        (NewMessageEvent event) -> {
            // use event.getMessage()
            return Unit.INSTANCE;
        });
        
// Dispose when you want to stop receiving events
disposable.dispose();
                    

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 disposable: Disposable = channelController
    .subscribeFor<NewMessageEvent> { newMessageEvent ->
        // use newMessageEvent.message
    }
    
// Dispose when you want to stop receiving events
disposable.dispose()
                    

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

Disposable disposable = channelController.subscribe((ChatEvent event) -> {
    if (event instanceof NewMessageEvent) {
        // use ((NewMessageEvent) event).getMessage()
    }
    return Unit.INSTANCE;
});

// Dispose when you want to stop receiving events
disposable.dispose();
                    

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 disposable: Disposable = channelController
    .subscribe { event: ChatEvent ->
        when (event) {
            is NewMessageEvent -> {
                // use event.message
            }
        }
    }

// Dispose when you want to stop receiving events
disposable.dispose()
                    

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.`);
                    

// Subscribe for User presence events
client.subscribeFor(
        new Class[]{UserPresenceChangedEvent.class},
        (ChatEvent chatEvent) -> {
            // Handle change
            return Unit.INSTANCE;
        }
);

// Subscribe for just the first ConnectedEvent
client.subscribeForSingle(ConnectedEvent.class,
        (ConnectedEvent event) -> {
            // Use event data
            int unreadCount = event.getMe().getTotalUnreadCount();
            int unreadChannels = event.getMe().getUnreadChannels();
            return Unit.INSTANCE;
        });
                    

// 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 for User presence events
client.subscribeFor<UserPresenceChangedEvent>() { event: UserPresenceChangedEvent ->
    // Handle change
}

// Subscribe for just the first ConnectedEvent
client.subscribeForSingle<ConnectedEvent> { event: ConnectedEvent ->
    // Use event data
    val unreadCount = event.me.totalUnreadCount
   val unreadChannels = event.me.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!');
    }
});
                    

client.subscribeFor(
        new Class[]{
                ConnectedEvent.class,
                ConnectingEvent.class,
                DisconnectedEvent.class
        },
        (ChatEvent chatEvent) -> {
            if (chatEvent instanceof ConnectedEvent) {
                // Socket is connected
            } else if (chatEvent instanceof ConnectingEvent) {
                // Socket is connecting
            } else if (chatEvent instanceof DisconnectedEvent) {
                // Socket is disconnected
            }
            return Unit.INSTANCE;
        }
);
                    

// 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.subscribeFor(
    ConnectedEvent::class,
    ConnectingEvent::class,
    DisconnectedEvent::class
) { 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);
                    

final Disposable disposable = client.subscribe(chatEvent -> {
    /* ... */
    return null;
});
disposable.dispose();
                    

// 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 disposable: Disposable = client.subscribe { /* ... */ }
disposable.dispose()
                    

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

subscription.cancel();