Coroutines in Android
Android Development with Compose: Architecture & Data
Course 5 ยท Chapter 3 ยท Doing Work Off the Screen
Real data takes time to arrive: a database read, a network call. If the app waits on the main thread, the screen freezes. Coroutines let code pause without blocking, and give the ViewModel a safe way to start work, stop it, and turn a stream of data into UI state.
The coroutine basics (suspend, launch, delay) come from the Kotlin courses; this chapter is about using them in an Android app.
viewModelScope cancels its coroutines when the ViewModel is cleared and is hardcoded to Dispatchers.Main; inject dispatchers and replace Main in tests with Dispatchers.setMain; repository code should be main-safe;
the data layer exposes suspend functions and Flows; build uiState with stateIn and WhileSubscribed(5000) for data that arrives as a stream; do not launch asynchronous work in a ViewModel's init or constructor; catch exceptions in coroutines; and for work of around five seconds or more use WorkManager.
The search did not cover Dispatchers.IO or Dispatchers.Default specifically, so that table is general knowledge. All code is unrun (no Kotlin compiler on the machine used to write this); nothing was seen on your install.
loadNotes() from init. It was placeholder code with no real waiting, so it was harmless there, but (docs) the guidance is not to launch asynchronous operations in a ViewModel's init or constructor. This chapter shows the shape to use once loading is real: the state is built from the data layer's Flow with stateIn.
Why Not Just Wait?
(general knowledge) The main thread draws the screen and handles taps. Block it for a few seconds and the app stops responding (Android may show an "application not responding" dialog). The fix is not a faster sleep; it is to not block.
A suspend function can pause at a point such as delay and let the thread do other work meanwhile. Only a coroutine (or another suspend function) can call it, which is why viewModelScope.launch is there.
viewModelScope
- (docs) Coroutines launched in
viewModelScopeare cancelled automatically when the ViewModel is cleared, so work does not outlive the screen that wanted it. - (docs) The scope is hardcoded to
Dispatchers.Main. That is fine for starting work and updating state; heavy work must move to another dispatcher. - (docs) A coroutine in this scope keeps running whether or not the UI is visible, until it finishes, is cancelled, or the ViewModel is cleared. For work of around five seconds or more that must finish regardless, the docs point to WorkManager (Android Development with Compose: Production & Publishing, planned).
Dispatchers and Main-Safety
| Dispatcher | Use it for |
|---|---|
Dispatchers.Main | The UI thread: updating state, light work. (docs: the default for viewModelScope) |
Dispatchers.IO | Waiting on disk or network (general knowledge) |
Dispatchers.Default | CPU-heavy work such as sorting or parsing a large list (general knowledge) |
(docs) The advice is that the data layer's functions should be main-safe: safe to call from the main thread, because they switch dispatchers themselves with withContext. The caller does not need to know. That is how FakeNotesRepository.addNote below is written.
The docs also say to inject the dispatcher rather than hard-code it, so a test can replace it:
A Repository That Exposes Suspend Functions and a Flow
notesis aFlow(docs: the data layer exposes suspend functions and Flows): the repository says "here is the list, and I will tell you when it changes".addNoteis a suspend function that does its slow work on the injected IO dispatcher.- It fails when the text is
"fail", so you can see the error path.
From Flow to UI State with stateIn
combine(general knowledge) merges the repository's notes with the current message into oneNotesUiStateeach time either changes.stateIn(...)(docs) turns that cold flow into aStateFlowthat the UI can collect. The docs' recommended policy for data arriving as a stream isSharingStarted.WhileSubscribed(5000): the upstream stays active for five seconds after the last collector goes away, which covers a rotation without restarting the work, but stops it if the user really leaves.initialValueis what the UI shows before the first emission, here the loading state.- Nothing is launched in
init: the work starts when something collectsuiState.
The Chapter 2 composables are unchanged: NotesRoute still calls collectAsStateWithLifecycle(). (general knowledge) The default value on the constructor parameter is what lets the standard viewModel() create this class without a factory (a class whose parameters all have defaults gets a no-argument constructor on the JVM); Chapter 9 replaces that with proper dependency injection.
Exceptions and Cancellation
(docs) Exceptions in coroutines should be caught, because an unhandled one can crash the app, and the docs' own sample rethrows CancellationException before catching general exceptions. (general knowledge) The reason: cancellation is delivered as a CancellationException; if you catch it as an ordinary error and carry on, the coroutine does not actually stop.
Here a failed save becomes a message in the UI state instead of a crash.
viewModelScope, lifecycleScope and the IO and Main dispatchers. In a Compose app you rarely need lifecycleScope: the ViewModel starts the work, and collectAsStateWithLifecycle() (Chapter 2) handles the UI side of the lifecycle.
Try It Yourself
Replace the Chapter 2 ViewModel with the stateIn version and add FakeNotesRepository. Run it, add a note, and report whether the screen stays responsive during the 300 ms delay and whether you see the loading state at start-up.
Add a note with the text fail and confirm the Snackbar from Chapter 2 shows "Could not save the note". Then remove the CancellationException branch and explain, in two sentences, what could go wrong.
Explain what WhileSubscribed(5_000) does when you rotate the device, and what it does when you press Home and wait a minute. Then explain why the docs advise against loading from init.
viewModelScope cancellation on clear; hardcoded to Main; inject dispatchers and Dispatchers.setMain in tests; main-safe repositories; suspend functions and Flows from the data layer; stateIn with WhileSubscribed(5000); no asynchronous work in init; catching coroutine exceptions and rethrowing CancellationException in a sample; WorkManager for work of about five seconds or more.General knowledge, not checked: the IO and Default dispatcher descriptions; the main-thread freezing explanation;
combine; why cancellation must not be swallowed; the default-parameter constructor remark; the import paths.Not verified: every listing and solution (unrun); the exercises (not run by me). Nothing was checked on your install.
Sources: Best practices for coroutines in Android (developer.android.com), Kotlin coroutines with lifecycle-aware components (developer.android.com), UI State production (developer.android.com), Recommendations for Android architecture (developer.android.com).
Flow, and the build setup it needs.