Write coroutines with Flow, StateFlow, and error handling
✓Works with OpenClaudeYou are a Kotlin coroutines expert. The user wants to write coroutines using Flow, StateFlow, and implement proper error handling patterns.
What to check first
- Verify
kotlinx-coroutines-coreis inbuild.gradle.kts:implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3") - Confirm Kotlin version is 1.9+ with
kotlin("jvm")plugin applied - Check that your scope (ViewModel, viewModelScope, etc.) is available for launching coroutines
Steps
- Create a Flow producer using
flow { }builder and emit values withemit() - Collect Flow with
collect { }inside a coroutine scope, handling each emitted value - Chain Flow operators like
map(),filter(), andcatch()before collection - Use
StateFlowinstead of Flow when you need state persistence and replay of the latest value - Implement error handling with
catch()operator to transform exceptions into emissions - Use
try-catchblocks aroundcollect()for uncaught exceptions in the collector - Apply
retryWhen()or custom retry logic to handle transient failures - Test flows using
turbinelibrary or manualtoList()for finite flows
Code
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
class UserRepository {
// Flow producer with error handling
fun fetchUsers(): Flow<List<String>> = flow {
emit(listOf("Loading..."))
delay(1000)
if (Math.random() > 0.3) {
emit(listOf("Alice", "Bob", "Charlie"))
} else {
throw Exception("Network error")
}
}
.catch { exception ->
emit(listOf("Error: ${exception.message}"))
}
.retryWhen { cause, attempt ->
attempt < 3 && cause is Exception
}
// StateFlow for managing UI state
private val _uiState = MutableStateFlow<String>("Idle")
val uiState: StateFlow<String> = _uiState.asStateFlow()
fun loadData() {
CoroutineScope(Dispatchers.Main).launch {
fetchUsers()
.map { users -> users.joinToString(", ") }
.collect { result ->
_uiState.value = result
}
}
}
}
// ViewModel usage with viewModelScope (recommended)
class UserViewModel(private val repo: UserRepository) : ViewModel() {
val users: Flow<List<String>> = repo.fetchUsers()
fun displayUsers() {
viewModelScope.launch {
try {
repo.fetchUsers()
.onStart { println("Loading...") }
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Kotlin / Android Skills
Other Claude Code skills in the same category — free to download.
Jetpack Compose
Build Jetpack Compose UIs with state and navigation
Room Database
Set up Room database with DAOs, entities, and migrations
Retrofit
Configure Retrofit for API calls with coroutines
Hilt DI
Set up Hilt dependency injection in Android
Kotlin Testing
Write Android tests with JUnit, Mockk, and Espresso
Kotlin Coroutines & Flow
Use Kotlin Coroutines and Flow for reactive async streams
Android Room Database
Set up Room (SQLite) for local data persistence in Android Kotlin apps
Want a Kotlin / Android skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.