CoursesAndroid from the foundation

Practice chapter 3 of 7

Threads, coroutines and Flow

Trace suspension and dispatch separately

A coroutine can suspend by retaining the state needed to continue later. Its thread is then available for other work. A dispatcher chooses where runnable continuations execute. Declaring a function suspend provides no automatic background thread for blocking code.

Worked example

On Main, delay(100) suspends without holding the main thread for 100 ms. Thread.sleep(100) blocks that thread. Use withContext(Dispatchers.IO) around a blocking file operation and return the result to the caller’s context.

Try it

A function marked suspend directly parses a large JSON string on Main. Why can scrolling still pause?

Compare your answer

The CPU work runs on the current dispatcher until it suspends or changes context. Move substantial CPU work to an appropriate dispatcher and measure the cost.

Source · Kotlin · Coroutine context and dispatchers

Make cancellation observable

A coroutine Job expresses a lifetime. Cancelling its owner signals children, but arbitrary running code must reach a cancellation check or a cancellable suspension point. Resource cleanup belongs in a finally block or another construct that runs on exit.

Worked example

A query changes from ca to cat. Cancel work for ca. A suspending delay observes cancellation promptly; a long CPU loop can check ensureActive between chunks. Also prevent an older result from overwriting the currently requested query.

Try it

Why can catching every exception and returning a fallback cause a stale result?

Compare your answer

The catch may swallow CancellationException and turn cancelled work into successful output. Propagate cancellation and handle the actual recoverable errors separately.

Source · Kotlin · Cancellation and timeouts

Decide who starts the producer

A cold flow begins its producer for each collection. A shared hot stream has a producer whose lifetime is controlled separately. StateFlow carries the latest state and can conflate successive equal values or let slow collectors skip intermediate states.

Worked example

Two screens collect flow { emit(loadNotes()) }. The load can run twice. Sharing it with stateIn in a suitable owner scope can give both collectors the same latest list; the chosen sharing policy controls when upstream runs.

Try it

A payment history must retain every confirmed payment. Is a StateFlow of the latest payment enough?

Compare your answer

Store every payment in a durable collection and expose the latest view of that collection as state. A latest-value stream alone cannot replay every historical transition.

Source · Android · StateFlow and SharedFlow