将kotlin协程和架构组件一起使用

前情提要: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, use androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0-beta01 or higher.
  • For LifecycleScope, use androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha01 or higher.
  • For liveData, use androidx.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

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

LifecycleScope is defined for each Lifecycle object. Any coroutine launched in this scope is canceled when the Lifecycle

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值