On this page

Watch channels

Use connect() to receive messages on a channel without joining as a member. The method subscribes to a message event listener and returns a function to disconnect.

Method signature

connect() 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.connect(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
AutoCloseable
Interface 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 messageSubscription = supportChannel.connect { message ->
8 // handle the new message received on the channel
9 println("New message received on 'support' channel: ${message.content}")
10 }
11
12 // The subscription can later be closed if needed
13 // messageSubscription.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 messageSubscription = supportChannel.connect { message ->
8 // handle the new message received on the channel
9 println("New message received on 'support' channel: ${message.content}")
10 }
11
12 // later, when you want to stop receiving messages:
13 messageSubscription.close()
14 println("Stopped receiving messages on 'support' channel.")
15
show all 19 lines
Last updated on