kotlin-coroutines
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseKotlin Coroutines Skill
Kotlin协程技能
Master asynchronous programming with structured concurrency.
掌握基于结构化并发的异步编程。
Topics Covered
涵盖主题
Structured Concurrency
结构化并发
kotlin
// ✅ Structured - cancellation propagates
class Repository(private val scope: CoroutineScope) {
suspend fun load() = withContext(Dispatchers.IO) { fetch() }
}
// ❌ Avoid GlobalScope
GlobalScope.launch { /* leaks */ }kotlin
// ✅ 结构化 - 取消操作会传播
class Repository(private val scope: CoroutineScope) {
suspend fun load() = withContext(Dispatchers.IO) { fetch() }
}
// ❌ 避免使用GlobalScope
GlobalScope.launch { /* 会导致泄漏 */ }Exception Handling
异常处理
kotlin
suspend fun loadData() = supervisorScope {
val a = async { fetchA() }
val b = async { fetchB() }
Result(a.awaitOrNull(), b.awaitOrNull())
}
// Never swallow CancellationException
catch (e: Exception) {
if (e is CancellationException) throw e
}kotlin
suspend fun loadData() = supervisorScope {
val a = async { fetchA() }
val b = async { fetchB() }
Result(a.awaitOrNull(), b.awaitOrNull())
}
// 切勿忽略CancellationException
catch (e: Exception) {
if (e is CancellationException) throw e
}Testing
测试
kotlin
@Test
fun test() = runTest {
val vm = ViewModel(testDispatcher)
vm.load()
advanceUntilIdle()
assertThat(vm.state.value.data).isNotNull()
}kotlin
@Test
fun test() = runTest {
val vm = ViewModel(testDispatcher)
vm.load()
advanceUntilIdle()
assertThat(vm.state.value.data).isNotNull()
}Troubleshooting
问题排查
| Issue | Resolution |
|---|---|
| Coroutine leak | Use structured scopes, not GlobalScope |
| Test hangs | Inject TestDispatcher, use advanceUntilIdle() |
| 问题 | 解决方法 |
|---|---|
| 协程泄漏 | 使用结构化作用域,不要使用GlobalScope |
| 测试挂起 | 注入TestDispatcher,使用advanceUntilIdle() |
Usage
使用方式
Skill("kotlin-coroutines")Skill("kotlin-coroutines")