ApiStream

Represents a persistent connection with a Kobweb server that you can continuously send and receive events on.

You must first define an API stream handler on the server side, and then you can connect to it from the client side with code like the following:

val stream = remember { ApiStream("echo") }
LaunchedEffect(Unit) {
    stream.connect(object : ApiStreamListener {
        override fun onConnected(ctx: ConnectedContext) { ... }
        override fun onTextReceived(ctx: TextReceivedContext) { ... }
        override fun onDisconnected(ctx: DisconnectedContext) { ... }
    }
}

Note that there's a shortcut for the case where you only need to handle the "onTextReceived" event:

LaunchedEffect(Unit) {
    stream.connect { text -> console.log("Got text from server: \"$text\"") }
}

While connected, you can call send to send messages to the server and disconnect to kill the stream connection.

If you call send BEFORE a stream finished connecting, what happens to the message (whether it gets enqueued or dropped) is configurable. See its header docs for more details.

Constructors

Link copied to clipboard
constructor(route: String)

Properties

Link copied to clipboard
open override val isConnected: Boolean
Link copied to clipboard
open override val route: String

Functions

Link copied to clipboard
suspend fun connect(streamListener: ApiStreamListener)
Link copied to clipboard
suspend fun ApiStream.connect(handleTextEvent: (ApiStreamListener.TextReceivedContext) -> Unit)
Link copied to clipboard
Link copied to clipboard
fun send(text: String, strategy: ApiStream.IfSentBeforeConnectedStrategy = IfSentBeforeConnectedStrategy.ENQUEUE)