Watch channels

Use onMessageReceived() to receive messages on a channel without joining as a member. The method subscribes to a message event listener and returns an AutoCloseable to stop receiving messages.

Deprecated method

connect() is deprecated. Use onMessageReceived() instead. Both methods have the same signature and behavior.

Method signature​

onMessageReceived() accepts a callback function as an argument. The Chat SDK invokes this callback whenever someone sends a message on the given channel. This function takes a single argument of a Message object.

This method takes the following parameters:

1channel.onMessageReceived(callback: (Message) -> Unit): AutoCloseable

Input​

* required
ParameterDescription
callback *
Type: (Message) -> Unit
Default:
n/a
Callback function passed as a parameter. It defines the custom behavior to be executed whenever a message is received on a channel.

Output​

TypeDescription
AutoCloseableInterface you can call to stop listening for new messages and clean up resources when they are no longer needed by invoking the close() method.

Sample code​

Start receiving messages on the support channel.

1// assume `chat` is an instance of your chat service or client
2// get the "support" channel asynchronously
3chat.getChannel("support").async { result ->
4 result.onSuccess { supportChannel ->
5 // handle success
6 // start receiving messages on the "support" channel
7 val subscription = supportChannel.onMessageReceived { message ->
8 // handle the new message received on the channel
9 println("New message received on 'support' channel: ${message.text}")
10 }
11
12 // The subscription can later be closed if needed
13 // subscription.close()
14 }.onFailure {
15 // handle failure
show all 17 lines

Other examples​

Stop receiving messages on the support channel.

1// assume `chat` is an instance of your chat service or client
2// get the "support" channel asynchronously
3chat.getChannel("support").async { result ->
4 result.onSuccess { supportChannel ->
5 // handle success
6 // start receiving messages on the "support" channel
7 val subscription = supportChannel.onMessageReceived { message ->
8 // handle the new message received on the channel
9 println("New message received on 'support' channel: ${message.text}")
10 }
11
12 // later, when you want to stop receiving messages:
13 subscription.close()
14 println("Stopped receiving messages on 'support' channel.")
15
show all 19 lines

Was this page useful?

Last updated on