Yokan / rebuild
Course 1 8624561

04-coroutines-flow.md

.codex/skills/compose-kotlin-agent-skills/references/04-coroutines-flow.md

documentation / design asset351 lines
1# Coroutines & Flow — Dispatchers, StateFlow, Error Handling23## Contents45- viewModelScope vs lifecycleScope6- Dispatchers — IO vs Default vs Main7- StateFlow vs SharedFlow vs Channel8- collectAsStateWithLifecycle9- stateIn and shareIn10- Error handling — Result, sealed errors11- Structured concurrency and cancellation1213## viewModelScope vs lifecycleScope1415| Scope | Tied to | Survives config change | Use for |16|-------|---------|----------------------|---------|17| `viewModelScope` | ViewModel lifecycle | Yes | Data loading, state updates, business logic |18| `lifecycleScope` | Activity/Fragment | No | UI-bound work (permissions, navigation side effects) |19| `rememberCoroutineScope()` | Composable | No | One-shot composable actions (scroll, animation) |2021```kotlin22// ViewModel — survives rotation23class AuthViewModel(private val repo: AuthRepository) : ViewModel() {24    init {25        viewModelScope.launch {26            repo.syncAccounts()  // survives config change27        }28    }29}3031// Composable — one-shot scroll32@Composable33fun AccountsList(accounts: List<AuthAccount>) {34    val listState = rememberLazyListState()35    val scope = rememberCoroutineScope()3637    LazyColumn(state = listState) { /* items */ }3839    FloatingActionButton(onClick = {40        scope.launch {41            listState.animateScrollToItem(0)  // UI-only, doesn't need ViewModel42        }43    })44}45```4647**Never use `GlobalScope`**. It ignores structured concurrency — coroutines leak.4849## Dispatchers5051| Dispatcher | Thread | Use for |52|-----------|--------|---------|53| `Dispatchers.Main` | Main/UI thread | UI updates, state emission, small logic |54| `Dispatchers.IO` | Shared IO pool (64+ threads) | Network calls, file I/O, DB (when not Room) |55| `Dispatchers.Default` | CPU cores pool | Heavy computation, JSON parsing, sorting large lists |56| `Dispatchers.Main.immediate` | Main, no re-dispatch | Already on Main, avoid queue hop |5758### When NOT to Switch Dispatchers5960```kotlin61// WRONG — Room already dispatches to background62viewModelScope.launch(Dispatchers.IO) {  // unnecessary thread hop63    val accounts = dao.getAllAccounts()64}6566// RIGHT — Room handles threading internally67viewModelScope.launch {68    val accounts = dao.getAllAccounts()  // Room moves to IO internally69}70```7172**Room, Retrofit (with suspend), and Ktor** handle dispatcher switching internally. Don't wrap them in `withContext(Dispatchers.IO)`.7374### When TO Switch7576```kotlin77// Heavy CPU work — parse 10k items78viewModelScope.launch {79    val parsed = withContext(Dispatchers.Default) {80        rawData.map { parseComplexItem(it) }  // CPU-bound81    }82    _state.update { it.copy(items = parsed) }83}8485// File I/O not wrapped by a library86viewModelScope.launch {87    val content = withContext(Dispatchers.IO) {88        File("large.json").readText()89    }90}91```9293## StateFlow vs SharedFlow vs Channel9495### StateFlow — UI State9697```kotlin98class AuthViewModel(private val repo: AuthRepository) : ViewModel() {99    private val _state = MutableStateFlow(AccountsUiState())100    val state: StateFlow<AccountsUiState> = _state.asStateFlow()101102    // Derived state from Room103    val accounts: StateFlow<List<AuthAccount>> = repo.getAllAccounts()104        .stateIn(105            scope = viewModelScope,106            started = SharingStarted.WhileSubscribed(5_000),107            initialValue = emptyList()108        )109110    fun onSearchChanged(query: String) {111        _state.update { it.copy(searchQuery = query) }112    }113}114```115116- Always has a value (`.value`)117- Conflates — if two rapid updates happen, collector only sees latest118- Replays latest value to new collectors119- Use for: any UI state120121### SharedFlow — Events to Multiple Subscribers122123```kotlin124class AnalyticsManager {125    private val _events = MutableSharedFlow<AnalyticsEvent>(126        replay = 0,          // no replay for new subscribers127        extraBufferCapacity = 64,128        onBufferOverflow = BufferOverflow.DROP_OLDEST129    )130    val events: SharedFlow<AnalyticsEvent> = _events.asSharedFlow()131132    suspend fun track(event: AnalyticsEvent) {133        _events.emit(event)134    }135}136```137138- No current value139- Multiple subscribers each get the event140- Configurable replay and buffer141- Use for: analytics, logging, broadcast events142143### Channel — One-Shot Commands144145```kotlin146class WorkoutViewModel : ViewModel() {147    private val _effects = Channel<UiEffect>(Channel.BUFFERED)148    val effects: Flow<UiEffect> = _effects.receiveAsFlow()149150    fun onWorkoutComplete() {151        viewModelScope.launch {152            _effects.send(UiEffect.NavigateToResults)153            _effects.send(UiEffect.PlayHaptic)154        }155    }156}157158// Collect in composable159LaunchedEffect(Unit) {160    viewModel.effects.collect { effect ->161        when (effect) {162            UiEffect.NavigateToResults -> navController.navigate("results")163            UiEffect.PlayHaptic -> haptics.success()164        }165    }166}167```168169- Delivered to exactly ONE collector170- Never dropped (unless channel is full with DROP strategy)171- Use for: navigation commands, snackbar, haptics — one-shot effects172173## collectAsStateWithLifecycle174175```kotlin176// WRONG — keeps collecting when app backgrounded177val state by viewModel.state.collectAsState()178179// RIGHT — stops collecting in onStop, resumes in onStart180val state by viewModel.state.collectAsStateWithLifecycle()181182// With custom lifecycle state183val state by viewModel.state.collectAsStateWithLifecycle(184    minActiveState = Lifecycle.State.RESUMED  // only collect when visible185)186```187188**Why this matters:** `collectAsState` keeps the flow active when app is in background. If the flow is expensive (location, sensor data, network polling), it wastes battery and CPU for invisible UI.189190**CMP exception:** in `commonMain`, `collectAsStateWithLifecycle` unavailable. Use `collectAsState` there. On Android targets, always use lifecycle-aware version.191192Dependency:193```toml194androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" }195```196197## stateIn and shareIn198199Convert cold Flow (Room query) to hot StateFlow for UI:200201```kotlin202// WRONG — new flow on every collector, Room query runs N times203val accounts: Flow<List<AuthAccount>> = repo.getAllAccounts()204205// RIGHT — shared, single Room query, all collectors share result206val accounts: StateFlow<List<AuthAccount>> = repo.getAllAccounts()207    .stateIn(208        scope = viewModelScope,209        started = SharingStarted.WhileSubscribed(5_000),210        initialValue = emptyList()211    )212```213214### SharingStarted Strategies215216| Strategy | Behavior | Use when |217|----------|----------|----------|218| `WhileSubscribed(5_000)` | Active while subscribed + 5s buffer | Default for most UI flows |219| `Eagerly` | Active immediately, never stops | App-wide state (auth, theme) |220| `Lazily` | Active on first subscriber, never stops | Data that should load once |221222**Why 5000ms?** Survives config change rotation (~2-3s) without restarting the upstream flow. Arbitrary but battle-tested.223224## Error Handling225226### Result + Sealed Domain Errors227228```kotlin229// Domain errors — NOT exceptions230sealed interface DomainError {231    data class Network(val code: Int, val message: String) : DomainError232    data object Unauthorized : DomainError233    data object NotFound : DomainError234    data class Unknown(val cause: Throwable) : DomainError235}236237// Repository returns Result238class AuthRepository(private val api: AuthApi, private val dao: AuthAccountDao) {239    suspend fun syncAccounts(): Result<List<AuthAccount>> {240        return try {241            val remote = api.getAccounts()242            val domain = remote.map { it.toDomain() }243            dao.insertAccounts(domain.map { it.toEntity() })244            Result.success(domain)245        } catch (e: HttpException) {246            when (e.code()) {247                401 -> Result.failure(DomainError.Unauthorized)248                404 -> Result.failure(DomainError.NotFound)249                else -> Result.failure(DomainError.Network(e.code(), e.message()))250            }251        } catch (e: IOException) {252            Result.failure(DomainError.Network(-1, "No connection"))253        }254    }255}256257// ViewModel handles Result258viewModelScope.launch {259    _state.update { it.copy(isLoading = true) }260    repo.syncAccounts()261        .onSuccess { accounts ->262            _state.update { it.copy(accounts = accounts, isLoading = false) }263        }264        .onFailure { error ->265            _state.update { it.copy(error = error, isLoading = false) }266        }267}268```269270### runCatching — Use with Caution271272```kotlin273// DANGEROUS — catches CancellationException, breaks structured concurrency274val result = runCatching { repo.fetchData() }275276// SAFE — rethrow CancellationException277suspend fun <T> safeRunCatching(block: suspend () -> T): Result<T> {278    return try {279        Result.success(block())280    } catch (e: CancellationException) {281        throw e  // never swallow this282    } catch (e: Throwable) {283        Result.failure(e)284    }285}286```287288**Critical:** `runCatching` and `try/catch(Throwable)` catch `CancellationException`. This silently breaks coroutine cancellation. Always rethrow `CancellationException`.289290## Structured Concurrency291292### Parallel Execution293294```kotlin295viewModelScope.launch {296    // WRONG — sequential, slow297    val accounts = repo.getAccounts()298    val settings = repo.getSettings()299300    // RIGHT — parallel301    val accountsDeferred = async { repo.getAccounts() }302    val settingsDeferred = async { repo.getSettings() }303    val accounts = accountsDeferred.await()304    val settings = settingsDeferred.await()305306    _state.update { it.copy(accounts = accounts, settings = settings) }307}308```309310### Cancellation311312```kotlin313class AuthViewModel : ViewModel() {314    private var searchJob: Job? = null315316    fun onSearchChanged(query: String) {317        searchJob?.cancel()  // cancel previous search318        searchJob = viewModelScope.launch {319            delay(300)  // debounce320            val results = repo.search(query)321            _state.update { it.copy(searchResults = results) }322        }323    }324}325```326327### SupervisorJob — Isolate Failures328329```kotlin330// WRONG — one child failure cancels sibling331viewModelScope.launch {332    launch { syncAccounts() }   // if this fails...333    launch { syncSettings() }   // ...this gets cancelled too334}335336// RIGHT — supervisor scope isolates failures337viewModelScope.launch {338    supervisorScope {339        launch { syncAccounts() }   // failure here...340        launch { syncSettings() }   // ...doesn't affect this341    }342}343```344345## Anti-Patterns346347- **Collecting Flow in `init {}` with manual launch** → use `stateIn` to convert to StateFlow348- **`delay()` for debouncing in ViewModel** → works but cancel/relaunch is manual. Consider `Flow.debounce()` or `Flow.distinctUntilChanged()`349- **`flowOn(Dispatchers.IO)` on Room Flow** → Room already dispatches. Double-hop350- **SharedFlow with `replay = 1` for UI state** → just use StateFlow. That's what it is351- **`collect {}` without lifecycle awareness** → use `collectAsStateWithLifecycle` or `repeatOnLifecycle`352

Search chapters, reference and source filenames.