协程Coroutine可以理解成轻量的线程,运行在线程中的非阻塞的Task;协程不会与特定的线程绑定,它可以在不同的线程之间灵活切换。
相关API:
CoroutineContext
CancellationException
Continuation
Job
Deferred
CoroutineScope.async
CoroutineScope.launch
Channel
Flow
suspendCoroutineUninterceptedOrReturn
suspendCoroutine
suspendCancellableCoroutine
Android相关
CoroutineScope(携程作用域)
1 | // Activity 中使用 lifecycleScope |
Dispatchers(调度器)
1 | withContext(Dispatchers.IO) { |
Job(任务)
1 | val job = launch { |
suspend
- 标记函数为挂起函数
- 可以调用其他挂起函数
- 不会创建新的协程
- 必须在协程或其他挂起函数中调用
1 | suspend fun getData(): String { |
async & launch区别
都用来创建新携程,但有以下区别:
- async 返回结果(Deferred)
- launch 不返回结果(Job)
- async 适合并行计算
- launch 适合执行不需要返回值的任务
1 | suspend fun loadDataParallel() = coroutineScope { |
repeatOnLifecycle
这个API特别适合需要在应用前台时执行,后台时暂停的场景,比如实时数据更新、轮询操作等
1 |
|