Langsung ke konten
Skillpedia
Pemrograman umum48k · #5012

kotlin-coroutines-expert

Fungsinya

Panduan ini mengajarkan cara menggunakan 'Coroutines' dan 'Flow' di Kotlin, yaitu alat untuk menjalankan beberapa tugas secara bersamaan tanpa membuat program macet. Panduan ini juga menunjukkan cara mengatur tugas-tugas tersebut, menangani error, dan menguji kode Anda.

Kapan dipakai

  • ✓Saat membangun program Kotlin yang perlu menjalankan beberapa operasi secara bersamaan.
  • ✓Saat menangani aliran data yang berubah seiring waktu.
  • ✓Saat men-debug masalah pada tugas yang dibatalkan atau gagal.

Link skill

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

Salin lalu tempelkan ke AI Anda (Claude, ChatGPT, atau Cursor) dan minta AI mengikuti instruksinya.

Cara pakai

Cara paling mudah: salin pesan ini dan tempelkan ke AI Anda. AI akan membaca skill dan mengikuti instruksinya.

Pesan siap tempel

Gunakan skill ini untuk membantu saya: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/kotlin-coroutines-expert/SKILL.md Baca file SKILL.md di link tersebut dan ikuti instruksinya untuk tugas saya.
Mau AI Anda menemukan skill seperti ini sendiri?Pasang MCP Skillpedia gratis: cukup satu baris, dan AI mencari di antara 15.000+ skill sebelum tiap tugas.Pasang dalam 1 menit →

Contoh permintaan ke AI

“Bagaimana cara menjalankan dua operasi jaringan secara bersamaan di Kotlin dan menangani kemungkinan error?”

5 skill baru setiap minggu. 1 menit baca.

Cara kerjanya

Alat ini menggunakan konsep yang disebut 'structured concurrency' agar tugas-tugas dikelola dengan benar. Anda juga belajar menggunakan 'Flow' untuk menangani data yang berurutan dan mengelola error dengan rapi.

Konten teknis (SKILL.md asli)

Teks asli dari pembuat, dalam bahasa Inggris, langsung dari 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.

Pertanyaan umum

Apa itu 'structured concurrency'?

Itu adalah cara mengatur tugas yang berjalan bersamaan, sehingga tugas-tugas tersebut dimulai dan dihentikan secara terkendali, seolah-olah menjadi bagian dari satu kelompok.

Apa perbedaan 'StateFlow' dan 'SharedFlow'?

'StateFlow' digunakan untuk menyimpan kondisi terkini dari sesuatu (misalnya teks di kotak pencarian), sedangkan 'SharedFlow' digunakan untuk mengirim event yang mungkin terjadi (misalnya klik tombol).

Mengapa saya sebaiknya tidak menggunakan 'GlobalScope'?

'GlobalScope' mengabaikan 'structured concurrency', sehingga tugas bisa terus berjalan padahal seharusnya sudah berhenti. Hal ini dapat menimbulkan masalah dan memory leak.

Detail

Deskripsi asli dari pembuat

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

repo: sickn33/agentic-awesome-skills

Popularitas

Bintang GitHub
48k
Peringkat
#5012
Lisensi
MIT
Diperbarui
15/10/2026

Apakah skill ini berguna?

0

Masuk untuk memberi suara.

Komentar

  • …

Skill lain dari repositori ini

Skill serupa