Skip to content
SkillImported

kotlin-coroutines-expert

Expert patterns for Kotlin Coroutines and Flow, covering structured concurrency, error handling, and testing.

Imported description, not reviewed yet

This item came from its original repository and was only scanned automatically; no editor has written an Arabic description for it yet. Read its content yourself before you rely on it. This page is not indexed by search engines until it is reviewed.

Download

Files: 1 · Size: 4.1 KB

Download the ZIP

The file carries the license of the original source.

Install

After downloading, run the command in a terminal. unzip asks before it replaces any file that is there.

  • For this project

    It goes in: .claude/skills/kotlin-coroutines-expert/

    mkdir -p .claude/skills && unzip ~/Downloads/kotlin-coroutines-expert.zip -d .claude/skills

  • For your account on the whole machine

    It goes in: ~/.claude/skills/kotlin-coroutines-expert/

    mkdir -p ~/.claude/skills && unzip ~/Downloads/kotlin-coroutines-expert.zip -d ~/.claude/skills

Instructions

Kotlin Coroutines Expert

Overview

A guide to mastering asynchronous programming with Kotlin Coroutines. Covers advanced topics like structured concurrency, Flow transformations, exception handling, and testing strategies.

When to Use This Skill

  • Use when implementing asynchronous operations in Kotlin.
  • Use when designing reactive data streams with Flow.
  • Use when debugging coroutine cancellations or exceptions.
  • Use when writing unit tests for suspending functions or Flows.

Step-by-Step Guide

1. Structured Concurrency

Always launch coroutines within a defined CoroutineScope. Use coroutineScope or supervisorScope to group concurrent tasks.

suspend fun loadDashboardData(): DashboardData = coroutineScope {
    val userDeferred = async { userRepo.getUser() }
    val settingsDeferred = async { settingsRepo.getSettings() }
    
    DashboardData(
        user = userDeferred.await(),
        settings = settingsDeferred.await()
    )
}

2. Exception Handling

Use CoroutineExceptionHandler for top-level scopes, but rely on try-catch within suspending functions for granular control.

val handler = CoroutineExceptionHandler { _, exception ->
    println("Caught $exception")
}

viewModelScope.launch(handler) {
    try {
        riskyOperation()
    } catch (e: IOException) {
        // Handle network error specifically
    }
}

3. Reactive Streams with Flow

Use StateFlow for state that needs to be retained, and SharedFlow for events.

// Cold Flow (Lazy)
val searchResults: Flow<List<Item>> = searchQuery
    .debounce(300)
    .flatMapLatest { query -> searchRepo.search(query) }
    .flowOn(Dispatchers.IO)

// Hot Flow (State)
val uiState: StateFlow<UiState> = _uiState.asStateFlow()

Examples

Example 1: Parallel Execution with Error Handling

suspend fun fetchDataWithErrorHandling() = supervisorScope {
    val task1 = async { 
        try { api.fetchA() } catch (e: Exception) { null } 
    }
    val task2 = async { api.fetchB() }
    
    // If task2 fails, task1 is NOT cancelled because of supervisorScope
    val result1 = task1.await()
    val result2 = task2.await() // May throw
}

Best Practices

  • ✅ Do: Use Dispatchers.IO for blocking I/O operations.
  • ✅ Do: Cancel scopes when they are no longer needed (e.g., ViewModel.onCleared).
  • ✅ Do: Use TestScope and runTest for unit testing coroutines.
  • ❌ Don't: Use GlobalScope. It breaks structured concurrency and can lead to leaks.
  • ❌ Don't: Catch CancellationException unless you rethrow it.

Troubleshooting

Problem: Coroutine test hangs or fails unpredictably. Solution: Ensure you are using runTest and injecting TestDispatcher into your classes so you can control virtual time.

Files

  • LICENSE1 KB
  • SKILL.md3 KB

Comments (0)

No comments yet. Be the first.

Sign in to comment. Commenting comes at level 1 (Member).

Report

Similar items

  • SkillImported

    android-cicd

    Automated Android CI/CD pipeline to Google Play — supports TWA, React Native, Flutter, and native Android. Run npx android-cicd to set up keystore generation, GitHub Secrets, and a multi-stage workflow (internal/alpha/beta/production) with

    MITFiles: 1

  • SkillImportedContains scripts

    app-store-optimization

    Complete App Store Optimization (ASO) toolkit for researching, optimizing, and tracking mobile app performance on Apple App Store and Google Play Store

    MITFiles: 13

  • SkillImported

    cli-creator

    Build a composable CLI for Codex from API docs, an OpenAPI spec, existing curl examples, an SDK, a web app, an admin tool, or a local script. Use when the user wants Codex to create a command-line tool that can run from any repo, expose com

    Apache-2.0Files: 4

  • SkillImported

    customer-inquiry-intake

    Reads a customer RFQ in whatever shape it arrived — a PDF drawing package, a 40-line spreadsheet, a portal export, a phone photo of a marked-up print, or a forwarded thread where the real requirement is four messages down — and pulls specif

    Apache-2.0Files: 4

  • SkillImported

    firebase-basics

    Sets up and develops projects using Firebase products and services, especially for mobile or web apps. Covers Firebase CLI setup, project configuration, and integration with Firebase platform services.

    MITFiles: 8

  • SkillImportedContains scripts

    flowio

    Reads, inspects, and writes Flow Cytometry Standard (FCS) 2.0, 3.0, and 3.1 files with FlowIO. Use for low-level FCS metadata and channel inspection, NumPy event extraction, multi-dataset files, table export, and FCS 3.1 creation; use FlowK

    BSD-3-ClauseFiles: 7