Streaming AI responses in Compose
Why it matters
- Users expect to see text appear word-by-word; a blocking
generateContentcall makes the UI feel frozen, while aFlowof chunks keeps the screen responsive. - Interviewers at product companies ask you to draw the full path: SDK
Flow→StateFlowin the ViewModel →collectAsStateWithLifecycle()in Compose, and to explain what happens on cancellation. - Streaming is where most AI-feature bugs live: null chunks, interleaved streams on double-tap, partial markdown that crashes the renderer, and memory growth from untrimmed history.
- For any provider behind your own backend (Claude, OpenAI, etc.) the app reads SSE or a chunked HTTP body with OkHttp or Ktor; knowing that shape lets you swap providers without touching the UI layer.
The simple explanation
- A streaming response is like a live caption feed at a conference.
- Each token is one word that pops up on the screen.
- The
Flowis the caption wire; theStateFlowis the caption board. - Cancellation is the user walking out of the room: the wire stops, the board keeps the last frame.
- A partial
**boldtag is a word split across two caption updates; you must wait for the closing**before rendering.
The core loop is: the AI SDK gives you a Flow<GenerateContentResponse>, you collect it inside viewModelScope, append each chunk's text to a StateFlow<UiState>, and Compose re-renders on every emission. For Firebase AI Logic the call is model.generateContentStream(prompt) (or chat.sendMessageStream(prompt) in a chat). For Claude, OpenAI, or any provider behind your own backend, the server streams SSE or a chunked HTTP body; the app reads it with OkHttp or Ktor and converts each chunk into the same Flow<String> shape so the UI layer never changes.
| Source | Stream type | Where the key lives |
|---|---|---|
Firebase AI Logic (generateContentStream) | Flow<GenerateContentResponse> | No Gemini key in the app; protect with App Check |
| Your backend (Claude, OpenAI, etc.) | SSE / chunked HTTP via OkHttp or Ktor | Server env var, never in the app |
Each GenerateContentResponse carries a piece of the answer. The text property can be null when a chunk has no text parts, so guard with ?: return@collect. Accumulate into a StateFlow so Compose's collectAsStateWithLifecycle() drives recomposition only while the screen is visible. When the user leaves the screen or sends a new message, cancel the coroutine; viewModelScope cancels on onCleared, but for mid-stream cancellation keep a Job reference and call job.cancel().
Partial markdown is the tricky part: a chunk may split a **bold** tag across two emissions. Use a streaming-safe renderer or buffer until the syntax is complete. Never feed raw model output to Html.fromHtml or a naive parser without sanitisation. Check the current docs for supported models and devices; the list changes frequently.
Notes
generateContentStream()returns aFlow<GenerateContentResponse>; the request runs when you callcollect. Collect it insideviewModelScope.launchso it is tied to the ViewModel lifecycle.- Each
GenerateContentResponse.textcan be null (a chunk with no text parts). Skip nulls withval chunk = resp.text ?: return@collectso the flow keeps running. - Accumulate chunks into a
StateFlow<UiState>via_ui.update { it.copy(streamingText = it.streamingText + chunk) }. Never write to a plainvar; Compose will not recompose. - Always re-throw
CancellationExceptionin the catch block. Swallowing it prevents the coroutine framework from cleaning up and can leak the upstream HTTP connection. - Use
collectAsStateWithLifecycle()(fromandroidx.lifecycle.compose) in the Composable. It stops observing theStateFlowwhen the screen is not visible. It does not stop the stream in the ViewModel. - For backend APIs (Claude, OpenAI, etc.) the app calls your own server; the server holds the secret key, enforces auth and rate limits, and streams SSE or a chunked body. Read it with OkHttp or Ktor. Never put a key in
BuildConfigor app code. - Keep a
Jobreference for the in-flight stream. When the user sends a new message, cancel the old job before launching the new one to prevent interleaved text. - Trim or summarise old chat turns before sending to the model to stay within the context window. Persist full history in Room; keep only a sliding window in memory.
- A chunk can split a markdown token (e.g.
**bo+ld**). Buffer until the syntax is closed or use a streaming-safe renderer. Never pass raw model text toHtml.fromHtmlwithout sanitisation. - Firebase AI Logic calls go through a Firebase proxy; enforce Firebase App Check so only your real app can call it.
Code example
This shows the three pieces that make streaming work in a Compose screen: a StateFlow-backed UI state, a ViewModel that collects the AI Flow and appends chunks, and a Composable that observes the state with collectAsStateWithLifecycle().
// ChatUiState + ChatViewModel + ChatScreen (combined for brevity)
data class ChatUiState(
val streamingText: String = "",
val isLoading: Boolean = false,
val error: String? = null,
)
class ChatViewModel(
private val model: GenerativeModel,
) : ViewModel() {
private val _ui = MutableStateFlow(ChatUiState())
val ui: StateFlow<ChatUiState> = _ui.asStateFlow()
fun send(text: String) {
viewModelScope.launch {
_ui.update { it.copy(isLoading = true, error = null, streamingText = "") }
try {
model.generateContentStream(text).collect { resp ->
val chunk = resp.text ?: return@collect // skip chunks with no text
_ui.update { it.copy(streamingText = it.streamingText + chunk) }
}
} catch (e: CancellationException) {
throw e // let the framework clean up
} catch (e: Exception) {
_ui.update { it.copy(error = e.message) }
} finally {
_ui.update { it.copy(isLoading = false) }
}
}
}
}
@Composable
fun ChatScreen(vm: ChatViewModel = viewModel()) {
val state by vm.ui.collectAsStateWithLifecycle()
Column {
if (state.isLoading) CircularProgressIndicator()
Text(text = state.streamingText) // partial text, re-renders per chunk
state.error?.let { Text(it, color = Color.Red) }
}
}return@collectskips chunks with nulltextwithout stopping the upstream flow.CancellationExceptionis re-thrown so the coroutine framework cancels the HTTP connection; thefinallyblock still resetsisLoading.collectAsStateWithLifecycle()stops observing when the screen is not visible, avoiding wasted recompositions.- Imports are left out for brevity;
GenerativeModelcomes fromcom.google.firebase.ai. - For a backend API, replace
model.generateContentStream(...)with an OkHttp or Ktor SSE reader that emits the sameFlow<String>; the UI layer stays identical.
Run the idea in plain Kotlin
class StreamSimulator(
private val chunks: List<String>,
) {
var cancelled = false
private set
fun process(): String {
val sb = StringBuilder()
for (chunk in chunks) {
if (cancelled) break
sb.append(chunk)
}
return sb.toString()
}
fun cancel() {
cancelled = true
}
}
fun main() {
val tokens = listOf("Hello", ", ", "world", "! ", "How ", "are ", "you", "?")
val full = StreamSimulator(tokens).process()
println("Full stream: " + full)
val sim = StreamSimulator(tokens)
val sb = StringBuilder()
for (i in 0..2) {
sb.append(tokens[i])
}
sim.cancel()
println("Partial: " + sb.toString())
println("Is cancelled: " + sim.cancelled)
}In production
- Users on low-RAM devices reported ANRs and
OutOfMemoryErrorafter long conversations. - The ViewModel held the full turn-by-turn history in a
MutableStateFlow<List<ChatTurn>>with no cap. - Each turn added text plus metadata; after many turns the in-memory list exceeded the heap budget.
- Crashlytics showed the spike correlated with long sessions.
- Introduced a sliding window of 20 turns in memory; full history was persisted to Room.
- Older turns were summarised into a single context string before being sent to the model.
- Added a memory monitor in the QA suite that flags any screen holding excessive chat state.
- The fix reduced peak heap usage for long sessions.
- Users who tapped the send button twice saw two streams interleaved in the same text field.
- The second
launchdid not cancel the first, so both coroutines wrote to the sameStateFlow. - The UI showed mixed sentences from two different prompts, confusing users and generating support tickets.
- Added a
Jobfield in the ViewModel; eachsend()call cancels the previous job before launching a new one. - Added a debounce on the send button to absorb accidental double-taps.
- Wrote a unit test that launches two streams concurrently and asserts only the latest one completes.
- The interleaving bug was eliminated in the next release.
Common mistakes
- Swallowing CancellationException. Catching and ignoring
CancellationExceptionprevents the coroutine framework from closing the upstream HTTP connection, leaking sockets and battery. Always re-throw it withthrow e. - Writing to a plain var instead of StateFlow. A
var streamingTextin the ViewModel is invisible to Compose; the screen never recomposes. UseStateFlowandcollectAsStateWithLifecycle()so the UI updates on every emission. - Not resetting streamingText on a new message. If you append to the old text instead of clearing it, the new response is concatenated to the previous one. Reset
streamingTextto empty string at the start of eachsend()call. - Rendering raw model output with Html.fromHtml. Model output can contain script tags or malformed HTML.
Html.fromHtmlis not a safe renderer. Use a sanitised markdown renderer or escape the text before display. - Forgetting to handle null text chunks.
GenerateContentResponse.textis nullable; some chunks carry no text. Appending it without a check puts the word "null" in the UI, and!!crashes. Guard with?: return@collect. - Storing the API key in BuildConfig or strings.xml. Any key shipped in the APK can be extracted with
apktool. Keys for Claude, OpenAI, or any provider must live only on the server. Firebase AI Logic keeps the Gemini key off the device; protect it with App Check.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How does streaming an AI response into a Compose UI work end-to-end?”
“What happens when the user navigates away mid-stream? How do you handle it?”
“A user sends a second message while the first response is still streaming. What do you do?”
“How do you render partial markdown that might have unclosed syntax?”
Quiz
What does generateContentStream() return in Firebase AI Logic?
What should you do when you catch a CancellationException inside the streaming collect block?
Where should the API key for Claude or OpenAI live in a production Android app?
A streamed chunk splits a markdown bold tag as 'bo' and 'ld'. What is the safest rendering strategy?
0 of 4 answered
Mini task
15-minute exercise: stream a response into a Compose text field
-
Create the state. Add a
data class ChatUiStatewithstreamingText: String,isLoading: Boolean, anderror: String?to your project. -
Build the ViewModel. Create a
ChatViewModelthat takes aGenerativeModel(from Firebase AI Logic or a fake for testing). Add aMutableStateFlow<ChatUiState>and a publicStateFlow. Implementsend(text: String)that resets the state, callsmodel.generateContentStream(text), and appends each non-nullresp.texttostreamingTextvia_ui.update. -
Handle cancellation. Wrap the
collectin atry / catch (CancellationException) / catch (Exception) / finallyblock. Re-throwCancellationException. Infinally, setisLoading = false. -
Build the Composable. Create a
ChatScreenthat callsvm.ui.collectAsStateWithLifecycle(). Show aCircularProgressIndicatorwhileisLoadingis true, renderstreamingTextin aTextcomposable, and showerrorin red if present. -
Test cancellation. Add a "Stop" button that calls
vm.cancel()(cancel the storedJob). Tap send, wait two seconds, tap stop. Confirm the text stops growing and the spinner disappears. -
Test double-send. Tap send twice quickly. Confirm the second response replaces the first (no interleaved text). If you see interleaving, add a
Jobfield and cancel the previous job at the start ofsend().
Done condition: Text appears token-by-token, the Stop button halts the stream, a double-tap does not interleave text, and no crash occurs when the response contains a partial **bold** tag (you may show the raw asterisks for now).