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()
returns an asynchronous stream which produces a new value whenever someone sends a message on the given channel.
This method takes the following parameters:
channel.connect() -> AsyncStream<MessageImpl>
Input
This method doesn't take any parameters.
Output
Parameter | Description |
---|---|
AsyncStream<MessageImpl> | An asynchronous stream that emits a new value whenever a new message is published in the current channel. |
Basic usage
Sample code
The code samples in Swift Chat SDK focus on asynchronous code execution.
You can also write synchronous code as the parameters are shared between the async and sync methods but we don't provide usage examples of such.
Start receiving messages on the support
channel.
- AsyncStream
- Closure
// Assuming you have a reference of type "ChatImpl" named "chat"
Task {
if let channel = try await chat.getChannel(channelId: "support") {
for await message in channel.connect() {
debugPrint("Received message: \(message)")
}
} else {
debugPrint("Channel 'support' not found")
}
}
// Important: Keep a strong reference to the returned "AutoCloseable" object as long as you want
// to receive updates. If the "AutoCloseable" is deallocated, the stream will be cancelled,
// and no further items will be produced. You can also stop receiving messages manually
// by calling the "close()" method on the "AutoCloseable" object.
// Assuming you have a reference of type "ChannelImpl" named "channel"
autoCloseable = channel.connect { message in
debugPrint("Received message: \(message.content)")
}