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