前情提要:kotlin协程和架构组件一起使用,完全都不用自己care取消耗时任务执行的问题,真香。
Use Kotlin coroutines with Architecture components
Kotlin coroutines provide an API that enables you to write asynchronous code. With Kotlin coroutines, you can define a CoroutineScope
, which helps you to manage when your coroutines should run. Each asynchronous operation runs within a particular scope.(协程都是运行在协程作用域中的)
Architecture components provide first-class support for coroutines for logical scopes in your app along with an interoperability layer with LiveData
. This topic explains how to use coroutines effectively with Architecture components.
Add KTX dependencies
The built-in coroutine scopes described in this topic are contained in the KTX extensions for each corresponding Architecture component. Be sure to add the appropriate dependencies when using these scopes.
- For
ViewModelScope
, useandroidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0-beta01
or higher. - For
LifecycleScope
, useandroidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha01
or higher. - For
liveData
, useandroidx.lifecycle:lifecycle-livedata-ktx:2.2.0-alpha01
or higher.
Lifecycle-aware coroutine scopes
Architecture components defines the following built-in scopes that you can use in your app.
ViewModelScope
A ViewModelScope
is defined for each ViewModel
in your app. Any coroutine launched in this scope is automatically canceled if the ViewModel
is cleared. Coroutines are useful here for when you have work that needs to be done only if the ViewModel
is active. For example, if you are computing some data for a layout, you should scope the work to the ViewModel
so that if the ViewModel
is cleared, the work is canceled automatically to avoid consuming resources.(ViewModelScope保证生命周期结束时,耗时任务被停止掉
)
You can access the CoroutineScope
of a ViewModel
through the viewModelScope
property of the ViewModel, as shown in the following example:(源码看文末注释1)
(CoroutineContext 作为参数构造了CoroutineScope,而
CoroutineContext 又是由Job + 调度器构造而来。launch和async都是CoroutineScope的扩展方法,见文末注释2,而withContext是顶层函数
)
class MyViewModel: ViewModel() {
init {
viewModelScope.launch {
// Coroutine that will be canceled when the ViewModel is cleared.
}
}
}
LifecycleScope
A LifecycleScope
is defined for each Lifecycle
object. Any coroutine launched in this scope is canceled when the Lifecycle