本文へスキップ
Skillpedia
一般的なプログラミング48k · #5012

kotlin-coroutines-expert

できること

このガイドでは、Kotlinで「コルーチン」と「Flow」を使う方法を学びます。これらは、プログラムを止めることなく複数の処理を同時に行うための仕組みです。タスクの整理方法、エラーの処理方法、コードのテスト方法も解説します。

使う場面

  • ✓複数の処理を並行して実行する必要があるKotlinプログラムを作るとき。
  • ✓時間とともに変化するデータの流れを扱うとき。
  • ✓キャンセルされたり失敗したりしたタスクの不具合を調べるとき。

スキルのリンク

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/kotlin-coroutines-expert/SKILL.md

コピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。

使い方

いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。

貼り付け用メッセージ

このスキルを使って手伝ってください:https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/kotlin-coroutines-expert/SKILL.md このリンクのSKILL.mdファイルを読んで、私の作業でその指示に従ってください。
こういうスキルを、AIが自分で見つけてくれたら?無料のSkillpedia MCPをインストール。1行で、作業の前に15,000+のスキルから探してくれます。1分でインストール →

AIへの頼み方の例

“Kotlinで2つのネットワーク処理を同時に実行し、起こりうるエラーを処理するにはどうすればよいですか?”

毎週5つの新しいスキル。1分で読めます。

仕組み

「構造化された並行処理」という考え方を使って、タスクが適切に管理されるようにします。また、順番に届くデータを扱う「Flow」の使い方や、エラーを整理して扱う方法も学びます。

技術的な内容(元のSKILL.md)

作者による元のテキスト(英語)をGitHubからそのまま表示しています。

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: CancellationException) { throw e } catch (e: IOException) { null }
    }
    val task2 = async { api.fetchB() }

    // A child failure does not directly cancel its siblings.
    // But an uncaught exception from await escapes the supervisor block and cancels it.
    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.

Limitations

  • Use this skill only when the task clearly matches the scope described above.
  • Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
  • Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.

Examples are fragments: supply imports, repository interfaces, Android lifecycle dependencies and the installed coroutines version. Handle each awaited failure deliberately and rethrow cancellation. SharedFlow replay/buffer choices determine delivery while no collector is active; it is not a guaranteed event queue. StateFlow conflates state changes. Test cancellation and slow/absent collectors, not only happy paths. Official exception behavior.

よくある質問

「構造化された並行処理」とは何ですか?

同時に実行されるタスクを、グループの一部であるかのように、制御された方法で開始し終了させるための整理の仕方です。

「StateFlow」と「SharedFlow」の違いは何ですか?

「StateFlow」は、検索ボックスの文字のように、今の状態を保持するために使います。「SharedFlow」は、ボタンのクリックのように、発生するイベントを送るために使います。

なぜ「GlobalScope」を使ってはいけないのですか?

「GlobalScope」は「構造化された並行処理」を無視するため、本来止まるべきタスクが動き続けてしまい、問題やメモリリークの原因になることがあります。

詳細

作者による元の説明

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

repo: sickn33/agentic-awesome-skills

人気

GitHubのスター
48k
ランキング
#5012
ライセンス
MIT
更新日
2026/10/15

このスキルは役に立ちますか?

0

ログイン して投票しましょう。

コメント

  • …

このリポジトリの他のスキル

似ているスキル