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:

channel.connect(
callback: @escaping (MessageImpl) -> Void
) -> AutoCloseable

Input

ParameterTypeRequiredDefaultDescription
callback(MessageImpl) -> VoidYesn/aCallback 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.

Basic usage

Start receiving messages on the support channel.

/// Assuming you have a "chat" instance available
/// Fetch the "support" channel and start receiving messages
chat?.getChannel(
channelId: "support"
) {
switch $0 {
case let .success(channel):
if let channel = channel {
debugPrint("Connecting to channel with ID: \(channel.id)")
let autoCloseable = channel.connect { message in
debugPrint("Received message: \(message.content)")
}
/// Store autoCloseable to stop receiving messages later if needed
} else {
debugPrint("Channel not found")
show all 20 lines

Other examples

Stop receiving messages on the support channel.

/// Assuming you have a "chat" instance available
/// and have previously connected to the 'support' channel
var autoCloseable: AutoCloseable?

// Fetch the "support" channel and start receiving messages
chat?.getChannel(
channelId: "support"
) {
switch $0 {
case let .success(channel):
if let channel = channel {
debugPrint("Connecting to channel with ID: \(channel.id)")
autoCloseable = channel.connect { message in
debugPrint("Received message: \(message.content)")
}
show all 26 lines
Last updated on