На основании кода, который я проследил, 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()
}
}
}