These code snippets will replace the existing snippets on the documentation pages
- https://getstream.io/chat/docs/event_listening/?language=kotlin
- https://getstream.io/chat/docs/event_listening/?language=java
Specific events
Disposable disposable = client.subscribeForSingle(NewMessageEvent.class,
(NewMessageEvent event) -> {
// use event.getMessage()
return Unit.INSTANCE;
});
// Dispose when you want to stop receiving events
disposable.dispose();
val disposable: Disposable = channelController
.subscribeFor<NewMessageEvent> { newMessageEvent ->
// use newMessageEvent.message
}
// Dispose when you want to stop receiving events
disposable.dispose()
All events at once
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();
val disposable: Disposable = channelController
.subscribe { event: ChatEvent ->
when (event) {
is NewMessageEvent -> {
// use event.message
}
}
}
// Dispose when you want to stop receiving events
disposable.dispose()
Client events
// 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
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
}
Connection changed
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;
}
);
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
}
}
}
Stop listening
final Disposable disposable = client.subscribe(chatEvent -> {
/* ... */
return null;
});
disposable.dispose();
val disposable: Disposable = client.subscribe { /* ... */ }
disposable.dispose()