android-coroutines
by livekit
Implement and review Kotlin Coroutines on Android: configure CoroutineScopes, manage Dispatchers, expose StateFlow/SharedFlow from ViewModels, collect with…
npx skills add https://github.com/livekit/client-sdk-android --skill android-coroutinesAndroid Coroutines Expert Skill
Workflow
- Identify scope — Determine the correct CoroutineScope (
viewModelScope,lifecycleScope, or injectedapplicationScope). - Wire data layer — Expose data as
suspendfunctions (one-shot) orFlow(streams) with injected Dispatchers. - Connect UI — Collect flows using
repeatOnLifecycle(Lifecycle.State.STARTED)and expose read-onlyStateFlow. - Verify — Run
./gradlew testand confirm coroutine behavior. If tests fail, check: uncaughtCancellationExceptionin genericcatchblocks,GlobalScopeusage causing leaked coroutines, missingawaitCloseincallbackFlow, or hardcoded Dispatchers breaking test determinism. Run./gradlew detektDebugto catch structural issues.
Critical Rules
1. Dispatcher Injection (Testability)
- NEVER hardcode Dispatchers (e.g.,
Dispatchers.IO,Dispatchers.Default) inside classes. - ALWAYS inject a
CoroutineDispatchervia the constructor. - DEFAULT to
Dispatchers.IOin the constructor argument for convenience, but allow it to be overridden.
// CORRECT
class UserRepository(
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) { ... }
// INCORRECT
class UserRepository {
fun getData() = withContext(Dispatchers.IO) { ... }
}
2. Main-Safety
- All suspend functions in Data/Domain layers must be main-safe — use
withContext(dispatcher)internally. - One-shot calls: expose as
suspendfunctions. Data streams: expose asFlow.
3. Lifecycle-Aware Collection
- NEVER collect a flow directly in
lifecycleScope.launchorlaunchWhenStarted(deprecated/unsafe). - ALWAYS use
repeatOnLifecycle(Lifecycle.State.STARTED)for collecting flows in Activities or Fragments.
// CORRECT
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.uiState.collect { ... }
}
}
4. ViewModel Scope Usage
- Use
viewModelScopefor initiating coroutines in ViewModels. - Do not expose suspend functions from the ViewModel to the View. The ViewModel should expose
StateFloworSharedFlowthat the View observes.
5. Mutable State Encapsulation
- NEVER expose
MutableStateFloworMutableSharedFlowpublicly. - Expose them as read-only
StateFloworFlowusing.asStateFlow()or upcasting.
6. GlobalScope Prohibition
- NEVER use
GlobalScope. It breaks structured concurrency and leads to leaks. - If a task must survive the current scope, use an injected
applicationScope(a custom scope tied to the Application lifecycle).
7. Exception Handling
- NEVER catch
CancellationExceptionin a genericcatch (e: Exception)block without rethrowing it. - Use
runCatchingonly if you explicitly rethrowCancellationException. - Use
CoroutineExceptionHandleronly for top-level coroutines (insidelaunch). It has no effect insideasyncor child coroutines.
8. Cancellability
- ALWAYS call
ensureActive()oryield()in tight loops (e.g., processing a large list, reading files). delay()andwithContext()are already cancellable — no extra checks needed there.
9. Callback Conversion
- Use
callbackFlowto convert callback-based APIs to Flow. - ALWAYS use
awaitCloseat the end of thecallbackFlowblock to unregister listeners.
Code Patterns
Repository Pattern with Flow
class NewsRepository(
private val remoteDataSource: NewsRemoteDataSource,
private val externalScope: CoroutineScope, // For app-wide events
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) {
val newsUpdates: Flow<List<News>> = flow {
val news = remoteDataSource.fetchLatestNews()
emit(news)
}.flowOn(ioDispatcher) // Upstream executes on IO
}
Parallel Execution
suspend fun loadDashboardData() = coroutineScope {
val userDeferred = async { userRepo.getUser() }
val feedDeferred = async { feedRepo.getFeed() }
// Wait for both
DashboardData(
user = userDeferred.await(),
feed = feedDeferred.await()
)
}
Testing with runTest
@Test
fun testViewModel() = runTest {
val testDispatcher = StandardTestDispatcher(testScheduler)
val viewModel = MyViewModel(testDispatcher)
viewModel.loadData()
advanceUntilIdle() // Process coroutines
assertEquals(expectedState, viewModel.uiState.value)
}