Coroutine 模块是 Kotlin 协程工具封装模块,提供了统一的线程池管理、协程调度器、异常处理机制和 Flow 扩展功能。该模块简化了协程的使用,提供了高效的线程管理策略和便捷的异常处理方案。
object Dispatcher {
// UI 主线程调度器
val UI: CoroutineDispatcher
// 获取串行处理 Handler
fun getSerialHandler(): Handler
// 通用线程池调度器
val WENEXT_THREAD_POOL: CoroutineDispatcher
// Handler 扩展方法
fun Handler.submit(runnable: Runnable, delay: Long = 0L)
fun Handler.remove(runnable: Runnable)
}
// 创建 IO 作用域
fun createIOScope(context: CoroutineContext = EmptyCoroutineContext): CoroutineScope
// 创建主线程作用域
fun createMainScope(context: CoroutineContext = EmptyCoroutineContext): CoroutineScope
// 带异常捕获的协程启动
fun CoroutineScope.launchWithCatch(
context: CoroutineContext = coroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): CoroutineCatcher
// 节流操作,防止频繁触发
fun <T> Flow<T>.throttleFirst(duration: Long): Flow<T>
// 在主线程执行
launch(Dispatcher.UI) {
// UI 操作
updateUI()
}
// 在后台线程执行
launch(Dispatcher.WENEXT_THREAD_POOL) {
// 耗时操作
val result = networkCall()
}
// 使用串行 Handler
val serialHandler = Dispatcher.getSerialHandler()
serialHandler.submit({
// 串行执行的任务
processData()
}, delay = 1000L)
// 创建 IO 作用域
val ioScope = createIOScope()
ioScope.launch {
// IO 操作
val data = loadFromDatabase()
}
// 创建主线程作用域
val mainScope = createMainScope()
mainScope.launch {
// 主线程操作
updateView()
}
// 链式异常处理
viewModelScope.launchWithCatch {
// 可能抛出异常的操作
val result = riskyOperation()
updateUI(result)
}.catch { context, throwable ->
// 统一异常处理
Log.e("TAG", "Coroutine error", throwable)
showError(throwable.message)
}
// 防止频繁点击
clickFlow
.throttleFirst(1000L) // 1秒内只响应第一次点击
.collect {
handleClick()
}
// 搜索防抖
searchFlow
.throttleFirst(300L) // 300ms 防抖
.collect { query ->
performSearch(query)
}
// 主线程池配置
ThreadPoolExecutor(
1, // 核心线程数
20.coerceAtLeast(AVAILABLE_PROCESSORS), // 最大线程数
3, TimeUnit.SECONDS, // 空闲超时
SynchronousQueue(), // 同步队列
NamedThreadFactory("wenext-thread-pool") // 命名工厂
)
// 备用线程池(用于拒绝策略)
ThreadPoolExecutor(
IO_CORE_POOL_SIZE,
IO_CORE_POOL_SIZE,
3, TimeUnit.SECONDS,
LinkedBlockingQueue(), // 无界队列
NamedThreadFactory("wenext-backup-thread-pool")
)
kotlinx.coroutines.core - Kotlin 协程核心库kotlinx.coroutines.android - Android 协程支持frame:base - 基础模块使用协程调度器frame:mvvm - MVVM 模块使用协程作用域implementation "com.wenext.android:frame-coroutine:6.0.0"