← The playbook

Kotlin & Architecture

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.

From disk to screennothing runs until the UI collects
DataCold flows from Room, DataStore and the network, on an injected IO dispatcher
DomainPlain Kotlin use cases: map, combine, flatMapLatest
ViewModelOne hot StateFlow of UiState, made with stateIn
UIcollectAsStateWithLifecycle on Android, AsyncSequence on iOS
data → domain → ViewModel → UI
Flows in the data and domain layers stay lazy and stateless. State exists in one place, the ViewModel.

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:

KOfflineFirstSearchRepository.ktKotlin
@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.

PrimitiveReplay & cachingConflationBest used for
Flow<T> (Cold)None (re-runs producer per collector)NoRepository data streams, database queries, multi-step use cases
StateFlow<T> (Hot)Always replays latest value (replay = 1), requires initial valueYes (skips equal values via equals())ViewModel UiState, current session state, feature flag snapshots
SharedFlow<T> (Hot)Configurable replay and bufferOptionalCross-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 policyUpstream lifecycle behaviorTrade-off on Android
SharingStarted.EagerlyStarts 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.LazilyWaits 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.
WhileSubscribed with a 5 second grace windowtwo things a user does
Rotates the phone
UI collectinggone ~300msUI collecting again
Upstream never stopped. No second query, no spinner. Presses Home
UI collectinggrace window, 5supstream cancelled
After the window, cursors and sockets are released.
The window is long enough to cover a configuration change and short enough to stop paying for a backgrounded app.

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:

KUiStateFlow.ktcore/ui/src/main/kotlin/coroutines
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(). Plain collectAsState() stays subscribed while the app is in the background, which defeats the whole policy.
  • For sensitive screens, WhileSubscribed also takes replayExpirationMillis. Set it to 0 and 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:

KSearchViewModel.kt:feature-search-ui
@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:

KCoroutineScopesModule.kt:core-common
@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.

KSuspendRunCatching.ktKotlin
// 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:

SSearchView.swiftSwift
// 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:

KSearchViewModelTest.ktKotlin
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.

Field guidewhat users or tests report → where to look first
The list flickers or reloads on rotationWhileSubscribed(0), or stateIn inside a getter
Search shows results for an older querya launch per keystroke instead of flatMapLatest
Battery drain with the app in the backgroundcollectAsState() or Eagerly on a live upstream
Unit tests pass locally and flake in CIa hardcoded dispatcher or a real delay
Work keeps running after the screen closesrunCatching swallowing cancellation, or GlobalScope
One failure silently stops a whole streamcatch placed outside flatMapLatest
A getter like val state get() = flow.stateIn(...) creates a new StateFlow, and a new upstream, on every read.