Kotlin Coroutines and Flow on Android: suspend, StateFlow and ViewModel
Quick answer: Use suspend functions for one-off work (an API call, a database write) and Flow for values that change over time (a Room query, a search box). Launch work in viewModelScope, switch to Dispatchers.IO only for blocking code, expose screen state as a StateFlow, and collect it with repeatOnLifecycle in an Activity or Fragment, or collectAsStateWithLifecycle() in Compose.
Coroutines are the standard way to run asynchronous work in Kotlin on Android. They replace callbacks, AsyncTask and most uses of RxJava with sequential, readable code. Flow extends them to streams of values. This guide covers what you need day to day, with an example that goes from the repository to the screen.
Why coroutines on Android?
- Asynchronous code reads like normal sequential code;
- Work is cancelled automatically when the screen or ViewModel goes away;
- Errors propagate with regular
try/catch; - Retrofit, Room, DataStore, WorkManager and Compose all support them natively.
1. Dependencies
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1")
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.7")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.7")
// for Compose: androidx.lifecycle:lifecycle-runtime-compose
}
Check for newer versions when you set up the project.
2. suspend functions
A suspend function can pause without blocking the thread, and resume later:
class UserRepository(private val api: ApiService) {
suspend fun loadUser(id: Int): User = api.getUser(id) // Retrofit suspend call
}
It can only be called from another suspend function or from a coroutine, for example one started in the ViewModel:
viewModelScope.launch {
val user = repository.loadUser(42)
_state.value = UiState.Success(user)
}
3. Dispatchers: which thread runs the code
| Dispatcher | Use for |
|---|---|
Dispatchers.Main | Updating the UI (the default in viewModelScope) |
Dispatchers.IO | Blocking I/O: files, legacy blocking APIs, raw JDBC/SQLite |
Dispatchers.Default | CPU-heavy work: parsing big JSON, sorting large lists, image processing |
Retrofit and Room suspend functions are already main-safe, so you don't need to wrap them. Wrap only blocking code, inside the repository:
suspend fun readConfig(file: File): String = withContext(Dispatchers.IO) {
file.readText()
}
4. What is Flow?
A Flow is a stream of values emitted over time. It is cold: nothing runs until someone collects it.
fun countdown(from: Int): Flow<Int> = flow {
for (i in from downTo 0) {
emit(i)
delay(1_000)
}
}
In real apps, you usually get flows from libraries: a Room DAO returning Flow<List<Note>>, DataStore preferences, or a StateFlow from a ViewModel.
5. Flow in the repository
class NoteRepository(private val dao: NoteDao, private val api: ApiService) {
val notes: Flow<List<Note>> = dao.observeAll() // updates when the table changes
suspend fun refresh() {
val remote = api.getNotes() // suspend Retrofit call
dao.insertAll(remote) // Flow above emits the new list
}
}
This is the "single source of truth" pattern: the screen always shows what is in the database, and the network only updates the database. See Room Database on Android.
6. UI state with StateFlow in the ViewModel
sealed interface NotesUiState {
data object Loading : NotesUiState
data class Success(val notes: List<Note>) : NotesUiState
data class Error(val message: String) : NotesUiState
}
class NotesViewModel(private val repo: NoteRepository) : ViewModel() {
val uiState: StateFlow<NotesUiState> = repo.notes
.map<List<Note>, NotesUiState> { NotesUiState.Success(it) }
.catch { emit(NotesUiState.Error(it.message ?: "Error")) }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), NotesUiState.Loading)
fun refresh() {
viewModelScope.launch {
try {
repo.refresh()
} catch (e: IOException) {
// keep showing cached notes; tell the user the refresh failed
}
}
}
}
stateIn turns the cold flow into a StateFlow that always has a current value. WhileSubscribed(5_000) keeps it alive for 5 seconds after the screen stops collecting, so a screen rotation doesn't restart the database query.
7. Collecting safely in an Activity or Fragment
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.uiState.collect { state ->
when (state) {
is NotesUiState.Loading -> showLoading()
is NotesUiState.Success -> showNotes(state.notes)
is NotesUiState.Error -> showError(state.message)
}
}
}
}
repeatOnLifecycle stops collecting when the app goes to the background and restarts when it returns. A plain lifecycleScope.launch { flow.collect {} } keeps collecting in the background, wasting resources and sometimes updating views that aren't visible. In a Fragment, use viewLifecycleOwner.lifecycleScope.
In Jetpack Compose:
@Composable
fun NotesScreen(viewModel: NotesViewModel) {
val state by viewModel.uiState.collectAsStateWithLifecycle()
// draw the UI from state
}
Flow vs. LiveData
| LiveData | StateFlow / Flow | |
|---|---|---|
| Lifecycle-aware | Built in | With repeatOnLifecycle or collectAsStateWithLifecycle |
| Operators | Few | Many (map, combine, debounce, flatMapLatest...) |
| Works outside Android | No | Yes (repositories, domain layer, tests, Kotlin Multiplatform) |
| Compose | Supported | The usual choice |
LiveData still works in existing code. For new code, StateFlow is the common choice.
A practical example: search as you type
private val query = MutableStateFlow("")
val results: StateFlow<List<Note>> = query
.debounce(300) // wait for the user to stop typing
.distinctUntilChanged()
.flatMapLatest { term -> repo.search(term) } // cancel the previous search
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
fun onQueryChanged(text: String) { query.value = text }
Flow operators handle what would otherwise take timers, flags and manual cancellation.
Common mistakes
- GlobalScope: work that is never cancelled and leaks; use
viewModelScopeorlifecycleScope; - runBlocking in app code: it blocks the thread, and on the main thread it freezes the app;
- Wrapping Retrofit or Room calls in withContext(IO): unnecessary, they are already main-safe;
- Catching CancellationException and ignoring it: catching
Exceptioninside a coroutine swallows cancellation; rethrow it or catch specific exceptions; - Collecting without lifecycle awareness: use
repeatOnLifecycle; - Exposing MutableStateFlow: keep it private and expose a read-only
StateFlow.
Combining Room and Retrofit
The typical modern stack: Retrofit with suspend functions for the network, Room with Flow for local data, a repository that saves network results in Room, and a ViewModel exposing StateFlow to the screen. See consuming a REST API with Retrofit.
Conclusion
With suspend functions for one-off work, Flow for data that changes, StateFlow for screen state and lifecycle-aware collection, asynchronous Android code becomes short, predictable and easy to cancel. Start by converting one screen, and the pattern repeats across the rest of the app.
Frequently asked questions
When should I use suspend and when Flow?
suspend for a single result (load a user, save a form). Flow for values that keep changing (a database query, user input, location updates).
StateFlow or SharedFlow?
StateFlow for state that always has a current value (what the screen shows). SharedFlow for one-time events (navigate, show a message).
Do I need Dispatchers.IO for Retrofit?
No. Retrofit's suspend functions already run the network call off the main thread.
Is LiveData deprecated?
No, but new code and Compose usually use StateFlow.
Why does my Flow keep running in the background?
It is collected without lifecycle awareness. Use repeatOnLifecycle(Lifecycle.State.STARTED) or collectAsStateWithLifecycle().