根据我跟踪的代码,lifecycleScope
将自动关闭ON_DESTROY
所以我从lifecycleScope
-> getOrCreateAndroidScope()
-> createAndBindAndroidScope
-> bindScope(scope)
->追踪lifecycle.addObserver(ScopeObserver(event, this, scope))
代码如下所示。
val LifecycleOwner.lifecycleScope: Scope
get() = getOrCreateAndroidScope()
private fun LifecycleOwner.getOrCreateAndroidScope(): Scope {
val scopeId = getScopeId()
return getKoin().getScopeOrNull(scopeId) ?: createAndBindAndroidScope(scopeId, getScopeName())
}
private fun LifecycleOwner.createAndBindAndroidScope(scopeId: String, qualifier: Qualifier): Scope {
val scope = getKoin().createScope(scopeId, qualifier, this)
bindScope(scope)
return scope
}
fun LifecycleOwner.bindScope(scope: Scope, event: Lifecycle.Event = Lifecycle.Event.ON_DESTROY) {
lifecycle.addObserver(ScopeObserver(event, this, scope))
}
class ScopeObserver(val event: Lifecycle.Event, val target: Any, val scope: Scope) :
LifecycleObserver, KoinComponent {
/**
* Handle ON_STOP to release Koin modules
*/
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() {
if (event == Lifecycle.Event.ON_STOP) {
scope.close()
}
}
/**
* Handle ON_DESTROY to release Koin modules
*/
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
if (event == Lifecycle.Event.ON_DESTROY) {
scope.close()
}
}
}