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.

What was checked, and how: read this first
Checked in the docs (one web search, summaries only): 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.
A correction to Chapter 2
The Chapter 2 ViewModel called 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?

// Blocking the main thread: the screen freezes while this runs fun addNote(text: String) { Thread.sleep(3000) // stands in for slow work _uiState.update { it.copy(notes = it.notes + text) } }

(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 without blocking the thread it runs on suspend fun addNote(text: String) { delay(3000) // pauses this coroutine only // ...then continues here } // Starting a coroutine from the ViewModel fun onAddClicked(text: String) { viewModelScope.launch { repository.addNote(text) } }

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

// What viewModelScope is, in outline // - created with the ViewModel // - cancelled automatically when the ViewModel is cleared // - runs on Dispatchers.Main by default
  • (docs) Coroutines launched in viewModelScope are 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

DispatcherUse it for
Dispatchers.MainThe UI thread: updating state, light work. (docs: the default for viewModelScope)
Dispatchers.IOWaiting on disk or network (general knowledge)
Dispatchers.DefaultCPU-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:

// Injecting the dispatcher so a test can replace it class FakeNotesRepository( private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO )

A Repository That Exposes Suspend Functions and a Flow

import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.withContext // A fake data source for now: Chapters 4 to 7 replace it with Room and Retrofit class FakeNotesRepository( private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO ) { private val _notes = MutableStateFlow(listOf("Buy milk", "Call Ada")) // A Flow: it emits the current list now and again after every change val notes: Flow<List<String>> = _notes.asStateFlow() // Main-safe: callers can use it from the main thread suspend fun addNote(text: String) = withContext(ioDispatcher) { delay(300) // pretend this is slow if (text == "fail") error("Could not save") _notes.update { it + text } } }
  • notes is a Flow (docs: the data layer exposes suspend functions and Flows): the repository says "here is the list, and I will tell you when it changes".
  • addNote is 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

import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch class NotesViewModel( private val repository: FakeNotesRepository = FakeNotesRepository() ) : ViewModel() { private val message = MutableStateFlow<String?>(null) // Built from the data layer's Flow: no loading code in init val uiState: StateFlow<NotesUiState> = combine(repository.notes, message) { notes, userMessage -> NotesUiState(notes = notes, isLoading = false, userMessage = userMessage) }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), initialValue = NotesUiState(isLoading = true) ) fun addNote(text: String) { if (text.isBlank()) { message.value = "A note cannot be empty" return } viewModelScope.launch { try { repository.addNote(text) } catch (e: CancellationException) { throw e // never swallow cancellation } catch (e: Exception) { message.value = "Could not save the note" } } } fun messageShown() { message.value = null } }
  • combine (general knowledge) merges the repository's notes with the current message into one NotesUiState each time either changes.
  • stateIn(...) (docs) turns that cold flow into a StateFlow that the UI can collect. The docs' recommended policy for data arriving as a stream is SharingStarted.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.
  • initialValue is what the UI shows before the first emission, here the loading state.
  • Nothing is launched in init: the work starts when something collects uiState.

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

try { repository.addNote(text) } catch (e: CancellationException) { throw e // let the cancellation pass through } catch (e: Exception) { message.value = "Could not save the note" }

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

Compared with the Classic UI course
Android Development: Architecture & Data 6 covers 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

Exercise 1

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.

๐Ÿ“„ View solution
Exercise 2

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.

๐Ÿ“„ View solution
Exercise 3

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.

๐Ÿ“„ View solution
Not Yet Verified
Checked in the docs (one web search, summaries only): 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).
Coming up
Chapter 4 replaces the fake repository's list with a real Room database: entities, a DAO that returns a Flow, and the build setup it needs.