Watch channels
You can let users watch a given channel and its messages using the connect() method, without the need to join the channel as members.
Under the hood, this method allows your app to receive messages on a given channel by subscribing it to a message event listener underneath to receive all message events of type text. This method also returns a function you can invoke to stop receiving message events and unsubscribe from the channel.
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
| Parameter | Description |
|---|---|
callback *Type: (Message) -> UnitDefault: 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
| Type | Description |
|---|---|
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 linesOther 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