Kotlin 协程与架构组件一起使用及底层原理分析,音视频开发前景

if (!isChangingConfigurations()) {

getViewModelStore().clear();

}

}

}

});

}

在Activity的生命周期走到onDestroy的时候调用ViewModelStore的clear做收尾工作。但是,注意一下,这个调用有个前提,此次走onDestroy不是因为配置更改才会去调用clear方法。

好的,到此为止,咱们理通了viewModelScope的协程是怎么做到自动取消的(ViewModel的mBagOfTags),以及是在什么时候进行取消的(ViewModel的clear()时)。

3. lifecycleScope

对于Lifecycle,Google贴心地提供了LifecycleScope,我们可以直接通过launch来创建Coroutine。

3.1 使用

举个简单例子,比如在Activity的onCreate里面,每隔100毫秒更新一下TextView的文字。

lifecycleScope.launch {

repeat(100000) {

delay(100)

tvText.text = “$it”

}

}

因为LifeCycle是可以感知组件的生命周期的,所以Activity一旦onDestroy了,相应的上面这个lifecycleScope。launch闭包的调用也会取消。

另外,lifecycleScope还贴心地提供了launchWhenCreated、launchWhenStarted、launchWhenResumed方法,这些方法的闭包里面有协程的作用域,它们分别是在CREATED、STARTED、RESUMED时被执行。

//方式1

lifecycleScope.launchWhenStarted {

repeat(100000) {

delay(100)

tvText.text = “$it”

}

}

//方式2

lifecycleScope.launch {

whenStarted {

repeat(100000) {

delay(100)

tvText.text = “$it”

}

}

}

不管是直接调用launchWhenStarted还是在launch中调用whenStarted都能达到同样的效果。

3.2 LifecycleScope的底层实现

先来看下lifecycleScope.launch是怎么做到的

/**

  • [CoroutineScope] tied to this [LifecycleOwner]'s [Lifecycle].

  • This scope will be cancelled when the [Lifecycle] is destroyed.

  • This scope is bound to

  • [Dispatchers.Main.immediate][kotlinx.coroutines.MainCoroutineDispatcher.immediate].

*/

val LifecycleOwner.lifecycleScope: LifecycleCoroutineScope

get() = lifecycle.coroutineScope

好家伙,又是扩展属性。这次扩展的是LifecycleOwner,返回了一个LifecycleCoroutineScope。每次在get的时候,是返回的lifecycle.coroutineScope,看看这个是啥。

/**

  • [CoroutineScope] tied to this [Lifecycle].

  • This scope will be cancelled when the [Lifecycle] is destroyed.

  • This scope is bound to

  • [Dispatchers.Main.immediate][kotlinx.coroutines.MainCoroutineDispatcher.immediate]

*/

val Lifecycle.coroutineScope: LifecycleCoroutineScope

get() {

while (true) {

val existing = mInternalScopeRef.get() as LifecycleCoroutineScopeImpl?

if (existing != null) {

return existing

}

val newScope = LifecycleCoroutineScopeImpl(

this,

SupervisorJob() + Dispatchers.Main.immediate

)

if (mInternalScopeRef.compareAndSet(null, newScope)) {

newScope.register()

return newScope

}

}

}

Lifecycle的coroutineScope也是扩展属性,它是一个LifecycleCoroutineScope。从注释可以看到,在Lifecycle被销毁之后,这个协程会跟着取消。这里首先会从mInternalScopeRef中取之前存入的缓存,如果没有再生成一个LifecycleCoroutineScopeImpl放进去,并调用LifecycleCoroutineScopeImpl的register函数。这里的mInternalScopeRef是Lifecycle类里面的一个属性: AtomicReference<Object> mInternalScopeRef = new AtomicReference<>(); (AtomicReference可以让一个对象保证原子性)。这里使用AtomicReference当然是为了线程安全。

既然生成的是LifecycleCorout

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值