Coroutines are the structured-concurrency model Android apps actually ship with. Flow is how you model streams of values over time (a ticker, a Room query, a WebSocket) without leaking collectors. This post sticks to the APIs you will use every week: viewModelScope, Dispatchers, StateFlow / SharedFlow, and collectAsStateWithLifecycle.
Structured concurrency first
A coroutine is not a thread. It is a suspendable task that runs in a scope. When the scope is cancelled, every child is cancelled. That is the feature you want when a screen is destroyed.
Advertisement
class TopicViewModel(
private val repository: TopicRepository,
) : ViewModel() {
private val _uiState = MutableStateFlow(TopicUiState())
val uiState: StateFlow<TopicUiState> = _uiState.asStateFlow()
fun refresh() {
viewModelScope.launch {
_uiState.update { it.copy(isLoading = true, error = null) }
runCatching { repository.fetchTopic() }
.onSuccess { topic ->
_uiState.update { it.copy(isLoading = false, topic = topic) }
}
.onFailure { error ->
_uiState.update { it.copy(isLoading = false, error = error.message) }
}
}
}
}viewModelScope is already bound to SupervisorJob + Dispatchers.Main.immediate. When the ViewModel is cleared, in-flight work is cancelled. You almost never need to cancel that job by hand.
Rules of thumb:
- Do not use
GlobalScopein an app. - Use
lifecycleScopefor work that should die with a UI controller, andviewModelScopefor work that should survive a configuration change. - Switch to
Dispatchers.IOonly at the boundary that actually blocks (disk, network via a blocking client). Retrofit and Room already exposesuspendfunctions — you usually stay on Main until you hit one of those.
Flow is a cold stream, StateFlow is a value
A Flow is cold: the producer starts when you collect, and each collector gets its own pipeline. A StateFlow is hot and always has a current value. Use StateFlow for screen state; use a plain Flow for one-shot or finite streams and for Room queries (dao.observeTopics(): Flow<List<Topic>>).
class TopicRepository(
private val api: TopicApi,
private val dao: TopicDao,
) {
fun observeTopics(): Flow<List<Topic>> = dao.observeAll()
suspend fun refresh() {
val remote = api.listTopics()
dao.upsertAll(remote)
}
}In the ViewModel, expose a single StateFlow to the UI:
val uiState: StateFlow<TopicUiState> = repository.observeTopics()
.map { topics -> TopicUiState(topics = topics) }
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = TopicUiState(),
)WhileSubscribed(5_000) keeps the upstream hot for five seconds after the last collector leaves, which is a good default for configuration changes.
Sharing events that are not state
Navigation events, snackbars, and "scroll to top" are one-shot. Putting them in StateFlow is how you show the same snackbar again after rotation. Use a SharedFlow with no replay (or a Channel exposed as a flow):
private val _events = MutableSharedFlow<UiEvent>()
val events = _events.asSharedFlow()
suspend fun showSaved() = _events.emit(UiEvent.Saved)Collect that flow in the screen with a LaunchedEffect and collectLatest, or use the official event-consumption patterns you already use in the project — but do not store the event in uiState unless you also model a "consumed" flag.
Collecting in Compose
Always collect with lifecycle awareness:
@Composable
fun TopicScreen(viewModel: TopicViewModel = hiltViewModel()) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
TopicList(state = uiState)
}collectAsStateWithLifecycle() stops collecting when the lifecycle is below STARTED. That avoids wasted work when the user backgrounds the app or a destination is on the back stack.
Cancellation and exceptions
launch in a scope with a SupervisorJob (like viewModelScope) isolates child failures: one failed refresh does not cancel the whole ViewModel. A failed child in a regular coroutineScope { } does cancel siblings — that is what you want for a paralleled "fetch both or fail".
suspend fun loadProfile(): Profile = coroutineScope {
val user = async { api.user() }
val stats = async { api.stats() }
Profile(user.await(), stats.await())
}If api.stats() throws, user is cancelled. Use supervisorScope if the two should be independent.
Flows are cancelled when the collector is cancelled. flow { } obeys cooperative cancellation between emissions. If you wrap a callback API, use callbackFlow and close the channel in awaitClose.
Coroutines feel like magic until a job outlives a screen. Stay in a scope, expose state as StateFlow, events as a fire-and-forget stream, and collect with collectAsStateWithLifecycle. That is the 90 percent path.
