kotlin-coroutines-expert
Skill này làm gì
Hướng dẫn này dạy cách dùng 'Coroutines' và 'Flow' trong Kotlin, là các công cụ để thực hiện nhiều tác vụ cùng lúc mà không làm chương trình bị treo. Nó chỉ cách tổ chức các tác vụ này, xử lý lỗi và kiểm thử code.
Khi nào nên dùng
- ✓Khi bạn xây dựng chương trình Kotlin cần thực hiện nhiều thao tác đồng thời.
- ✓Khi làm việc với các luồng dữ liệu thay đổi theo thời gian.
- ✓Khi gỡ lỗi các tác vụ bị hủy hoặc thất bại.
Liên kết skill
https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/kotlin-coroutines-expert/SKILL.mdSao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.
Cách dùng
Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.
Tin nhắn có sẵn để dán
Dành cho Claude Code, Codex hoặc Cursor: chạy lệnh trong thư mục dự án của bạn và skill sẽ được cài đặt.
Tải tệp SKILL.md về và thả vào thư mục skill của agent.
Ví dụ cách nhờ AI
“Làm thế nào để thực hiện hai thao tác mạng cùng lúc trong Kotlin và xử lý các lỗi có thể xảy ra?”
5 skill mới mỗi tuần. Đọc chỉ 1 phút.
Cách hoạt động
Nó dùng một khái niệm gọi là 'structured concurrency' để đảm bảo các tác vụ được quản lý đúng cách. Bạn cũng học cách dùng 'Flow' để xử lý dữ liệu tuần tự và quản lý lỗi một cách có tổ chức.
Nội dung kỹ thuật (SKILL.md gốc)
Lấy nguyên văn từ GitHub, do tác giả viết 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.
Câu hỏi thường gặp
'Structured concurrency' là gì?
Đó là cách tổ chức các tác vụ chạy đồng thời, đảm bảo chúng được bắt đầu và dừng theo cách có kiểm soát, như thể chúng thuộc cùng một nhóm.
Khác nhau giữa 'StateFlow' và 'SharedFlow' là gì?
'StateFlow' dùng để giữ trạng thái hiện tại của một thứ gì đó (như nội dung trong ô tìm kiếm), còn 'SharedFlow' dùng để gửi các sự kiện có thể xảy ra (như một lần nhấn nút).
Vì sao không nên dùng 'GlobalScope'?
'GlobalScope' bỏ qua 'structured concurrency', có thể khiến các tác vụ tiếp tục chạy khi không nên, gây ra vấn đề và rò rỉ bộ nhớ.
Chi tiết
Mô tả gốc của tác giả
Expert patterns for Kotlin Coroutines and Flow, covering structured concurrency, error handling, and testing.
Độ phổ biến
- Sao GitHub
- 48k
- Vị trí xếp hạng
- #5012
- Giấy phép
- MIT
- Cập nhật
- 15/10/2026
Bình luận
- …
Thêm skill từ kho mã này
00-andruia-consultant
48kGiúp agent của bạn bắt đầu hoặc cải thiện các dự án AI. Phân tích mã, gợi ý công cụ và lập kế hoạch hành động bằng tiếng Tây Ban Nha.
007
48kCho phép agent của bạn thực hiện kiểm toán bảo mật và mô hình hóa mối đe dọa. Hữu ích để bảo vệ dự án khỏi các cuộc tấn công và lỗ hổng.
10-andruia-skill-smith
48kGiúp agent của bạn tạo hoặc cải thiện các công cụ AI. Xác định cách công cụ hoạt động, viết tài liệu và kiểm tra cấu trúc.
20-andruia-niche-intelligence
48kGiúp agent của bạn tạo bản tóm tắt về một ngành cụ thể. Hữu ích để hiểu bối cảnh, quy tắc, cách người dùng tương tác và rủi ro của dự án.
Skill tương tự
diffs
394kGiúp agent của bạn tạo một diff có thể chia sẻ về các chỉnh sửa, dưới dạng liên kết xem hoặc file ảnh, thay vì một bản tóm tắt viết tay.
coding-agent
394kGiúp agent của bạn giao một việc lập trình lớn cho Codex, Claude Code hoặc OpenCode chạy nền, rồi theo dõi tiến độ của nó.
gh-issues
394kGiúp agent của bạn tìm issue trên GitHub, chọn những issue cần xử lý và mở pull request với bản sửa, kể cả theo dõi nhận xét đánh giá.