Structured concurrency and Kotlin Flow at scale
Coroutines and Flow hold a modern Android app together, and a Kotlin Multiplatform core even more so. They replaced callbacks and RxJava chains with code you can read from top to bottom. In a large codebase they still go wrong in quiet ways: a scope that outlives its screen, a hardcoded dispatcher, a flow shared with the wrong policy. You find out later, as a leak, a drained battery or a flaky test. These are the rules I hold to when I modernize an app or build a shared core, and at the end, a field guide for spotting what goes wrong when they're missing.
Inject dispatchers
A withContext(Dispatchers.IO) written straight into a repository is one of the most common reasons unit tests are slow and flaky. On the JVM that call hops onto a real thread pool, outside the virtual clock that runTest controls.
Pass the dispatcher in through the constructor instead, with a qualifier:
@Qualifier@Retention(AnnotationRetention.BINARY)annotation class IoDispatcher@Qualifier@Retention(AnnotationRetention.BINARY)annotation class DefaultDispatcherinternal class OfflineFirstSearchRepository @Inject constructor( private val dao: SearchDao, private val api: SearchApi, @IoDispatcher private val ioDispatcher: CoroutineDispatcher,) : SearchRepository { override fun observeRecentQueries(): Flow<List<String>> = dao.observeRecent() .flowOn(ioDispatcher) override suspend fun refreshIndex(): Unit = withContext(ioDispatcher) { val remote = api.fetchIndex() dao.replaceAll(remote.map { it.toEntity() }) }}In production Hilt binds Dispatchers.IO. In a test you pass StandardTestDispatcher(testScheduler), and every coroutine runs on one thread, in order, with no real waiting.
Pick the right holder
I often see a ViewModel with several MutableStateFlow properties plus a SharedFlow or Channel for one-off navigation events. Screen state ends up spread across streams that know nothing about each other, and events get dropped on rotation.
| Primitive | Replay & caching | Conflation | Best used for |
|---|---|---|---|
Flow<T> (Cold) | None (re-runs producer per collector) | No | Repository data streams, database queries, multi-step use cases |
StateFlow<T> (Hot) | Always replays latest value (replay = 1), requires initial value | Yes (skips equal values via equals()) | ViewModel UiState, current session state, feature flag snapshots |
SharedFlow<T> (Hot) | Configurable replay and buffer | Optional | Cross-component broadcast buses in a core module (e.g., auth logout trigger) |
Let WhileSubscribed manage the upstream
When a ViewModel turns cold flows into a hot StateFlow<UiState> with stateIn, the SharingStarted policy decides when the database queries, sockets and sensor listeners upstream start and stop. Pick wrong and you either leak work in the background or reload everything on each rotation.
| Sharing policy | Upstream lifecycle behavior | Trade-off on Android |
|---|---|---|
SharingStarted.Eagerly | Starts immediately when the ViewModel is created and runs until viewModelScope is cleared. | Wastes battery, CPU, and network bandwidth while the app sits in the background. |
SharingStarted.Lazily | Waits for the first subscriber, then stays active until viewModelScope is cleared. | Avoids startup work if unobserved, but still keeps upstream work running after the user presses Home. |
WhileSubscribed(0) | Cancels the upstream flow the exact millisecond the last collector disappears. | Tears down and restarts the entire pipeline on every rotation, causing UI flicker and duplicate requests. |
WhileSubscribed(StopTimeoutMillis) | Keeps the upstream flow alive for a short grace window after the last collector leaves. | Bridges configuration changes seamlessly while still releasing background resources once the window expires. |
Don't scatter 5_000 across dozens of ViewModels. Give it one name, or inject a SharingStarted from :core-ui, so every screen behaves the same and tests can override it:
private const val StopTimeoutMillis: Long = 5_000L/** * Keeps upstream flows alive across brief configuration changes (such as rotation * or theme switches) while cancelling background work once the UI stays stopped. */val DefaultWhileSubscribed: SharingStarted = SharingStarted.WhileSubscribed(stopTimeoutMillis = StopTimeoutMillis)class SearchViewModel( observeRecentQueries: ObserveRecentQueriesUseCase, sharingStarted: SharingStarted = DefaultWhileSubscribed,) : ViewModel() { private val queryInput = MutableStateFlow("") val uiState: StateFlow<SearchUiState> = combine( queryInput, observeRecentQueries(), ) { query, recent -> SearchUiState(query = query, recentQueries = recent) }.stateIn( scope = viewModelScope, started = sharingStarted, initialValue = SearchUiState(), ) fun onQueryChanged(query: String) { queryInput.value = query }}A few things to pair with it:
- Collect in Compose with
collectAsStateWithLifecycle(). PlaincollectAsState()stays subscribed while the app is in the background, which defeats the whole policy. - For sensitive screens,
WhileSubscribedalso takesreplayExpirationMillis. Set it to0and the cached value is wiped as soon as the upstream stops.
Let the latest query win
Search is where most apps first get concurrency wrong. Launch a coroutine per keystroke and the responses race: type "kot" then "kotlin", and if the shorter query answers last, the screen shows the wrong results. The fix isn't a lock or a request counter. It's choosing the operator that matches the intent:
@OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class)val results: StateFlow<SearchResults> = queryInput .map { it.trim() } .debounce(300) // wait until typing pauses .distinctUntilChanged() // "kotlin " and "kotlin" are the same search .flatMapLatest { query -> // a new query cancels the old request if (query.length < 2) { flowOf(SearchResults.Idle) } else { searchCatalog.stream(query) .map<List<SearchResult>, SearchResults> { SearchResults.Loaded(it) } .onStart { emit(SearchResults.Loading) } .catch { emit(SearchResults.Failed) } // a failed search doesn't end the stream } } .stateIn(viewModelScope, DefaultWhileSubscribed, SearchResults.Idle)flatMapLatest cancels the previous inner flow the moment a new query arrives, so a stale response can never overwrite a fresh one. The catch sits inside it on purpose. Put it outside and one failed request ends the whole search stream, and the screen goes quiet until the user leaves and comes back.
Work that outlives a screen
Some work has to finish even if the user leaves: revoking a token on sign-out, flushing analytics, saving a draft. The tempting shortcut is GlobalScope, which nobody can cancel, test or see. I give the app one injected scope instead:
@Qualifier@Retention(AnnotationRetention.BINARY)annotation class ApplicationScope@Module@InstallIn(SingletonComponent::class)object CoroutineScopesModule { @Provides @Singleton @ApplicationScope fun applicationScope(@DefaultDispatcher dispatcher: CoroutineDispatcher): CoroutineScope = CoroutineScope(SupervisorJob() + dispatcher)}class SessionRepository @Inject constructor( @ApplicationScope private val appScope: CoroutineScope, private val api: SessionApi,) { fun signOut() { // Finishes even if the screen that asked for it is already gone appScope.launch { api.revokeToken() } }}The SupervisorJob keeps one failed task from cancelling the others, and because the scope is injected, a test can pass in a TestScope and assert the work actually ran. Anything that must survive the process itself, like an upload, belongs in WorkManager instead.
The runCatching trap
Structured concurrency only works if CancellationException travels up the hierarchy when a scope is cancelled. The standard runCatching catches Throwable, so it swallows cancellation and hands you a Result.failure. Put that inside a loop or a retry and the coroutine keeps running after the user has left the screen.
// Safe suspend wrapper that rethrows CancellationExceptioninline fun <T> suspendRunCatching(block: () -> T): Result<T> = try { Result.success(block())} catch (c: CancellationException) { throw c} catch (t: Throwable) { Result.failure(t)}For parallel work inside a repository, use coroutineScope when one failure should cancel the siblings, and supervisorScope when partial results are fine.
Crossing into Swift
In a shared core, repositories in commonMain expose Flow<T>. Objective-C interop doesn't understand coroutines or a generic Flow. With the SKIE compiler plugin on the shared framework, every public Flow<T> arrives in Swift as an AsyncSequence that follows Swift's own structured concurrency:
// SwiftUI View consuming a shared Kotlin Flow via SKIEstruct SearchView: View { @State private var state = SearchUiState.companion.initial() let viewModel: SharedSearchPresenter var body: some View { SearchListContent(state: state) .task { // Automatically subscribes on appear and cancels the Kotlin Flow on disappear for await newState in viewModel.uiState { self.state = newState } } }}When the SwiftUI view goes away, Swift cancels the .task, and SKIE turns that into a cancel on the Kotlin job underneath.
Tests that never sleep
With injected dispatchers and cold flows, no unit test needs Thread.sleep(). With kotlinx-coroutines-test and Turbine you assert the exact sequence of states:
class SearchViewModelTest { @get:Rule val mainDispatcherRule = MainDispatcherRule() // viewModelScope needs a test Main dispatcher @Test fun `emits the initial state, then the typed query`() = runTest { val repository = FakeSearchRepository(results = listOf(SearchResult("1", "Compose"))) val viewModel = SearchViewModel( observeRecentQueries = ObserveRecentQueriesUseCase(repository), ) viewModel.uiState.test { assertEquals(SearchUiState(), awaitItem()) viewModel.onQueryChanged("comp") assertEquals("comp", awaitItem().query) cancelAndIgnoreRemainingEvents() } }}Symptoms and their usual causes
When I join a codebase, these are the reports that point straight at a coroutine problem. Each one maps to a rule above.
WhileSubscribed(0), or stateIn inside a getterflatMapLatestcollectAsState() or Eagerly on a live upstreamdelayrunCatching swallowing cancellation, or GlobalScopecatch placed outside flatMapLatestval state get() = flow.stateIn(...) creates a new StateFlow, and a new upstream, on every read.