Streaming AI responses in Compose

Stream AI text token-by-token into Jetpack Compose with Kotlin Flow, handle cancellation in ViewModel, and render partial markdown safely in Android. About 25 minutes.

Why it matters

  • Users expect to see text appear word-by-word; a blocking generateContent call makes the UI feel frozen, while a Flow of chunks keeps the screen responsive.
  • Interviewers at product companies ask you to draw the full path: SDK Flow → StateFlow in 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 Flow is the caption wire; the StateFlow is the caption board.
  • Cancellation is the user walking out of the room: the wire stops, the board keeps the last frame.
  • A partial **bold tag 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.

SourceStream typeWhere 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 KtorServer 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 a Flow<GenerateContentResponse>; the request runs when you call collect. Collect it inside viewModelScope.launch so it is tied to the ViewModel lifecycle.
  • Each GenerateContentResponse.text can be null (a chunk with no text parts). Skip nulls with val chunk = resp.text ?: return@collect so the flow keeps running.
  • Accumulate chunks into a StateFlow<UiState> via _ui.update { it.copy(streamingText = it.streamingText + chunk) }. Never write to a plain var; Compose will not recompose.
  • Always re-throw CancellationException in the catch block. Swallowing it prevents the coroutine framework from cleaning up and can leak the upstream HTTP connection.
  • Use collectAsStateWithLifecycle() (from androidx.lifecycle.compose) in the Composable. It stops observing the StateFlow when 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 BuildConfig or app code.
  • Keep a Job reference 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 to Html.fromHtml without 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@collect skips chunks with null text without stopping the upstream flow.
  • CancellationException is re-thrown so the coroutine framework cancels the HTTP connection; the finally block still resets isLoading.
  • collectAsStateWithLifecycle() stops observing when the screen is not visible, avoiding wasted recompositions.
  • Imports are left out for brevity; GenerativeModel comes from com.google.firebase.ai.
  • For a backend API, replace model.generateContentStream(...) with an OkHttp or Ktor SSE reader that emits the same Flow<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

OOM crash after long chat sessions
  • Users on low-RAM devices reported ANRs and OutOfMemoryError after 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.
The fix
  • 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.
Garbled text when the user double-taps send
  • Users who tapped the send button twice saw two streams interleaved in the same text field.
  • The second launch did not cancel the first, so both coroutines wrote to the same StateFlow.
  • The UI showed mixed sentences from two different prompts, confusing users and generating support tickets.
The fix
  • Added a Job field in the ViewModel; each send() 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 CancellationException prevents the coroutine framework from closing the upstream HTTP connection, leaking sockets and battery. Always re-throw it with throw e.
  • Writing to a plain var instead of StateFlow. A var streamingText in the ViewModel is invisible to Compose; the screen never recomposes. Use StateFlow and collectAsStateWithLifecycle() 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 streamingText to empty string at the start of each send() call.
  • Rendering raw model output with Html.fromHtml. Model output can contain script tags or malformed HTML. Html.fromHtml is not a safe renderer. Use a sanitised markdown renderer or escape the text before display.
  • Forgetting to handle null text chunks. GenerateContentResponse.text is 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

  1. Create the state. Add a data class ChatUiState with streamingText: String, isLoading: Boolean, and error: String? to your project.

  2. Build the ViewModel. Create a ChatViewModel that takes a GenerativeModel (from Firebase AI Logic or a fake for testing). Add a MutableStateFlow<ChatUiState> and a public StateFlow. Implement send(text: String) that resets the state, calls model.generateContentStream(text), and appends each non-null resp.text to streamingText via _ui.update.

  3. Handle cancellation. Wrap the collect in a try / catch (CancellationException) / catch (Exception) / finally block. Re-throw CancellationException. In finally, set isLoading = false.

  4. Build the Composable. Create a ChatScreen that calls vm.ui.collectAsStateWithLifecycle(). Show a CircularProgressIndicator while isLoading is true, render streamingText in a Text composable, and show error in red if present.

  5. Test cancellation. Add a "Stop" button that calls vm.cancel() (cancel the stored Job). Tap send, wait two seconds, tap stop. Confirm the text stops growing and the spinner disappears.

  6. Test double-send. Tap send twice quickly. Confirm the second response replaces the first (no interleaved text). If you see interleaving, add a Job field and cancel the previous job at the start of send().

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).

Next: Function calling and tools