Stream answers in the Android SDK
Show an agent's answer as it is written by collecting the Kotlin Flow from OctoClient.streamChat, with cancellation and UI state tips.
Working draft. These docs are illustrative: names, endpoints and examples describe the intended behaviour and can change before launch.
Streaming sends the answer to your app in small pieces while the agent is still writing it. Customers see text appear after a moment instead of waiting for the full reply. Use streamChat for any chat screen where the answer can be more than a sentence long.
Collect a stream
streamChat returns a cold Flow of StreamEvent. Nothing is sent until you collect it.
viewModelScope.launch {
val text = StringBuilder()
octo.streamChat(text = "How do I change my plan?", conversationId = cid)
.catch { e -> _state.value = UiState.Failed(e as? OctoError) }
.collect { event ->
when (event) {
is StreamEvent.MessageDelta -> {
text.append(event.text)
_state.value = UiState.Writing(text.toString())
}
is StreamEvent.MessageDone -> _state.value = UiState.Done(event.message)
is StreamEvent.ToolCall -> Unit
is StreamEvent.Error -> _state.value = UiState.Failed(event.error)
}
}
}
Each MessageDelta holds the next piece of text. MessageDone arrives once with the complete Message, including its sources. Replace your partial text with that message so the final text always matches what the server stored.
What you should see
The first delta arrives shortly after the request starts. Deltas continue until MessageDone, then the flow completes. The streaming events page lists every case in detail.
Cancel a stream
The stream stops when the collecting coroutine is cancelled. Keep the Job if the customer can press a stop button.
private var streamJob: Job? = null
fun stop() {
streamJob?.cancel()
}
Cancelling closes the connection. The text received so far stays in your UI state, and the conversation keeps the messages that were completed.
Keep the UI responsive
- Update a single piece of state, such as a
StateFlow, instead of editing a list on every delta. - Collect on the main dispatcher. The SDK already does its network work off the main thread.
- Disable the send button while a stream is running, or queue the next message until
MessageDone. - Resume after a configuration change from your
ViewModel. Do not restart the request inonCreate.
Under the hood
The SDK reads the same server-sent events as the REST API and maps message.delta, message.done, tool.call and error to StreamEvent. It stops at the [DONE] marker. If you need the raw format, see Streaming in the API reference.
Tip: Use
chatfor short, non-visual calls such as a background check, andstreamChatwhere a person watches the answer appear.