coroutines-patterns

Kotlin Coroutines and Flow patterns for structured concurrency, error handling, and async operations.

Safety Notice

This listing is imported from skills.sh public index metadata. Review upstream SKILL.md and repository scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "coroutines-patterns" with this command: npx skills add ahmed3elshaer/everything-claude-code-mobile/ahmed3elshaer-everything-claude-code-mobile-coroutines-patterns

Coroutines Patterns

Structured concurrency for Kotlin.

Coroutine Scopes

// ✅ ViewModel scope (auto-cancelled)
class HomeViewModel : ViewModel() {
    fun loadData() {
        viewModelScope.launch {
            // Cancelled when ViewModel cleared
        }
    }
}

// ✅ Lifecycle scope
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycleScope.launch {
            // Cancelled when lifecycle destroyed
        }
    }
}

// ❌ AVOID: GlobalScope
GlobalScope.launch { }  // Never cancelled, memory leaks

Dispatchers

// Main - UI operations
withContext(Dispatchers.Main) {
    textView.text = "Updated"
}

// IO - Network, disk
withContext(Dispatchers.IO) {
    api.fetchData()
    database.query()
}

// Default - CPU intensive
withContext(Dispatchers.Default) {
    list.sortedBy { it.score }
}

Flow Patterns

// StateFlow for UI state
private val _state = MutableStateFlow(HomeState())
val state: StateFlow<HomeState> = _state.asStateFlow()

// SharedFlow for events
private val _events = MutableSharedFlow<Event>()
val events: SharedFlow<Event> = _events.asSharedFlow()

// Collect with lifecycle
@Composable
fun HomeScreen(viewModel: HomeViewModel) {
    val state by viewModel.state.collectAsStateWithLifecycle()
}

Flow Operators

flow
    .filter { it.isActive }
    .map { transform(it) }
    .distinctUntilChanged()
    .debounce(300)
    .catch { emit(fallback) }
    .collect { process(it) }

Error Handling

// Try-catch in coroutine
viewModelScope.launch {
    try {
        val result = repository.fetchData()
        _state.value = Success(result)
    } catch (e: Exception) {
        _state.value = Error(e.message)
    }
}

// supervisorScope - siblings don't cancel
supervisorScope {
    launch { task1() }  // Failure doesn't cancel task2
    launch { task2() }
}

Cancellation

// Cooperative cancellation
suspend fun processItems(items: List<Item>) {
    items.forEach { item ->
        ensureActive()  // Check cancellation
        process(item)
    }
}

// CancellationException handling
try {
    coroutineWork()
} catch (e: CancellationException) {
    throw e  // Don't swallow!
} catch (e: Exception) {
    handleError(e)
}

Remember: Structured concurrency = lifecycle-bound, cancellable, debuggable.

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

Coding

kmp-repositories

No summary provided by upstream source.

Repository SourceNeeds Review
Coding

kmp-networking

No summary provided by upstream source.

Repository SourceNeeds Review
Coding

gradle-patterns

No summary provided by upstream source.

Repository SourceNeeds Review
Coding

kmp-di

No summary provided by upstream source.

Repository SourceNeeds Review