$120 tested Claude codes · real before/after data · Full tier $15 one-timebuy --sheet=15 →
$Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. download --free →
clskills.sh — terminal v2.4 — 2,347 skills indexed● online
[CL]Skills_
Kotlin / AndroidintermediateNew

Kotlin Coroutines

Share

Write coroutines with Flow, StateFlow, and error handling

Works with OpenClaude

You 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-core is in build.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

  1. Create a Flow producer using flow { } builder and emit values with emit()
  2. Collect Flow with collect { } inside a coroutine scope, handling each emitted value
  3. Chain Flow operators like map(), filter(), and catch() before collection
  4. Use StateFlow instead of Flow when you need state persistence and replay of the latest value
  5. Implement error handling with catch() operator to transform exceptions into emissions
  6. Use try-catch blocks around collect() for uncaught exceptions in the collector
  7. Apply retryWhen() or custom retry logic to handle transient failures
  8. Test flows using turbine library or manual toList() 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

Quick Info

Difficultyintermediate
Version1.0.0
AuthorClaude Skills Hub
kotlincoroutinesflow

Install command:

curl -o ~/.claude/skills/kotlin-coroutines.md https://clskills.in/skills/kotlin/kotlin-coroutines.md

Related Kotlin / Android Skills

Other Claude Code skills in the same category — free to download.

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.