kotlin-coroutines-expert – skill Lập trình cho agent AI
Các mẫu chuyên sâu về Kotlin Coroutines và Flow, bao gồm structured concurrency, xử lý lỗi và kiểm thử.
Cài skill kotlin-coroutines-expert bằng một lệnh
Chọn công cụ bạn đang dùng, copy lệnh và dán vào terminal. Skill sẽ nằm trong thư mục skills của công cụ đó và sẵn sàng dùng ở phiên làm việc tiếp theo.
Claude Code
mkdir -p ~/.claude/skills && curl -fsSL https://skill.dn1nguoi.com/z/kotlin-coroutines-expert-7011b.tgz | tar xz -C ~/.claude/skills
Gọi trong Claude Code: /kotlin-coroutines-expert – rồi mô tả công việc bạn muốn làm.
Codex
mkdir -p ~/.codex/skills && curl -fsSL https://skill.dn1nguoi.com/z/kotlin-coroutines-expert-7011b.tgz | tar xz -C ~/.codex/skills
Gọi trong Codex: $kotlin-coroutines-expert – rồi mô tả công việc bạn muốn làm.
Hermes Agent
mkdir -p ~/.hermes/skills && curl -fsSL https://skill.dn1nguoi.com/z/kotlin-coroutines-expert-7011b.tgz | tar xz -C ~/.hermes/skills
Gọi trong Hermes Agent: /kotlin-coroutines-expert – rồi mô tả công việc bạn muốn làm.
DeepSeek
mkdir -p ~/.deepcode/skills && curl -fsSL https://skill.dn1nguoi.com/z/kotlin-coroutines-expert-7011b.tgz | tar xz -C ~/.deepcode/skills
Gọi trong DeepSeek: /kotlin-coroutines-expert – rồi mô tả công việc bạn muốn làm.
Nội dung SKILL.md
Nội dung SKILL.md gốc bằng tiếng Anh.
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.IOfor blocking I/O operations. - ✅ Do: Cancel scopes when they are no longer needed (e.g.,
ViewModel.onCleared). - ✅ Do: Use
TestScopeandrunTestfor unit testing coroutines. - ❌ Don't: Use
GlobalScope. It breaks structured concurrency and can lead to leaks. - ❌ Don't: Catch
CancellationExceptionunless 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](https://kotlinlang.org/docs/exception-handling.html).
Skill liên quan
- vendor-management – Dùng khi xem xét, chấm điểm hoặc kiểm toán quan hệ với nhà cung cấp SaaS/bên thứ ba…
- langchain-architecture – Làm chủ framework LangChain để xây dựng ứng dụng LLM phức tạp với agent, chain, memory…
- vpe-review – /c-level-agents:vpe-review [plan] — Rà soát kế hoạch ưu tiên thông lượng của VP of…
- learn – Giúp người dùng học một chủ đề qua kèm cặp thích ứng, lập kế hoạch bài học, luyện tập…
- legacy-modernizer – Tái cấu trúc mã nguồn cũ, di chuyển framework lỗi thời và triển khai hiện đại hóa từng…
- leiloeiro-avaliacao – Tổ chức bằng chứng và các kịch bản định giá tham khảo cho bất động sản đấu giá, với giới…
- weekly-review – Dùng khi ai đó muốn chạy đánh giá hàng tuần, khép các việc còn mở, rà soát dự án và cam…
- leiloeiro-risco – Phân tích rủi ro đấu giá bất động sản. Thang điểm 40 điểm, rủi ro pháp lý/tài chính/vận…