coroutines-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Coroutines Patterns

协程模式

Structured concurrency for Kotlin.
适用于Kotlin的结构化并发。

Coroutine Scopes

协程作用域

kotlin
// ✅ ViewModel scope (auto-cancelled)
class HomeViewModel : ViewModel() {
    fun loadData() {
        viewModelScope.launch {
            // Cancelled when ViewModel cleared
        }
    }
}

// ✅ Lifecycle scope
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycleScope.launch {
            // Cancelled when lifecycle destroyed
        }
    }
}

// ❌ AVOID: GlobalScope
GlobalScope.launch { }  // Never cancelled, memory leaks
kotlin
// ✅ ViewModel scope(自动取消)
class HomeViewModel : ViewModel() {
    fun loadData() {
        viewModelScope.launch {
            // 当ViewModel被销毁时自动取消
        }
    }
}

// ✅ Lifecycle作用域
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycleScope.launch {
            // 当生命周期销毁时自动取消
        }
    }
}

// ❌ 避免使用:GlobalScope
GlobalScope.launch { }  // 永远不会取消,会造成内存泄漏

Dispatchers

调度器

kotlin
// Main - UI operations
withContext(Dispatchers.Main) {
    textView.text = "Updated"
}

// IO - Network, disk
withContext(Dispatchers.IO) {
    api.fetchData()
    database.query()
}

// Default - CPU intensive
withContext(Dispatchers.Default) {
    list.sortedBy { it.score }
}
kotlin
// Main - UI操作
withContext(Dispatchers.Main) {
    textView.text = "Updated"
}

// IO - 网络、磁盘操作
withContext(Dispatchers.IO) {
    api.fetchData()
    database.query()
}

// Default - CPU密集型操作
withContext(Dispatchers.Default) {
    list.sortedBy { it.score }
}

Flow Patterns

Flow模式

kotlin
// StateFlow for UI state
private val _state = MutableStateFlow(HomeState())
val state: StateFlow<HomeState> = _state.asStateFlow()

// SharedFlow for events
private val _events = MutableSharedFlow<Event>()
val events: SharedFlow<Event> = _events.asSharedFlow()

// Collect with lifecycle
@Composable
fun HomeScreen(viewModel: HomeViewModel) {
    val state by viewModel.state.collectAsStateWithLifecycle()
}
kotlin
// StateFlow用于管理UI状态
private val _state = MutableStateFlow(HomeState())
val state: StateFlow<HomeState> = _state.asStateFlow()

// SharedFlow用于事件处理
private val _events = MutableSharedFlow<Event>()
val events: SharedFlow<Event> = _events.asSharedFlow()

// 结合生命周期收集流
@Composable
fun HomeScreen(viewModel: HomeViewModel) {
    val state by viewModel.state.collectAsStateWithLifecycle()
}

Flow Operators

Flow操作符

kotlin
flow
    .filter { it.isActive }
    .map { transform(it) }
    .distinctUntilChanged()
    .debounce(300)
    .catch { emit(fallback) }
    .collect { process(it) }
kotlin
flow
    .filter { it.isActive }
    .map { transform(it) }
    .distinctUntilChanged()
    .debounce(300)
    .catch { emit(fallback) }
    .collect { process(it) }

Error Handling

错误处理

kotlin
// Try-catch in coroutine
viewModelScope.launch {
    try {
        val result = repository.fetchData()
        _state.value = Success(result)
    } catch (e: Exception) {
        _state.value = Error(e.message)
    }
}

// supervisorScope - siblings don't cancel
supervisorScope {
    launch { task1() }  // Failure doesn't cancel task2
    launch { task2() }
}
kotlin
// 在协程中使用try-catch
viewModelScope.launch {
    try {
        val result = repository.fetchData()
        _state.value = Success(result)
    } catch (e: Exception) {
        _state.value = Error(e.message)
    }
}

// supervisorScope - 子协程失败不会取消其他兄弟协程
supervisorScope {
    launch { task1() }  // 失败不会取消task2
    launch { task2() }
}

Cancellation

取消操作

kotlin
// Cooperative cancellation
suspend fun processItems(items: List<Item>) {
    items.forEach { item ->
        ensureActive()  // Check cancellation
        process(item)
    }
}

// CancellationException handling
try {
    coroutineWork()
} catch (e: CancellationException) {
    throw e  // Don't swallow!
} catch (e: Exception) {
    handleError(e)
}

Remember: Structured concurrency = lifecycle-bound, cancellable, debuggable.
kotlin
// 协作式取消
suspend fun processItems(items: List<Item>) {
    items.forEach { item ->
        ensureActive()  // 检查取消状态
        process(item)
    }
}

// CancellationException异常处理
try {
    coroutineWork()
} catch (e: CancellationException) {
    throw e  // 不要吞掉该异常!
} catch (e: Exception) {
    handleError(e)
}

注意: 结构化并发 = 绑定生命周期、可取消、可调试。