Koin 的生命周期范围与活动范围。他们是一样的吗?

Ely*_*lye 4 android android-lifecycle kotlin koin koin-scope

我正在从https://github.com/InsertKoinIO/koin/blob/master/koin-projects/docs/reference/koin-android/scope.md学习 Koin 的范围

如果我有一个 Koin 模块如下

val myModule =
    module {
        scope<MyActivity> { scoped { Presenter() } }
    }
Run Code Online (Sandbox Code Playgroud)

在我的活动中,我可以做到这一点

class MyActivity : AppCompatActivity() {

    private val presenter by lazy {
        lifecycleScope.get<Presenter>(Presenter::class.java)
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

或者我可以使用this.scopewhere thisis MyActivityobject。

class MyActivity : AppCompatActivity() {

    private val presenter by lazy {
        this.scope.get<Presenter>(Presenter::class.java)
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

我测试过它们是一样的。两者是一样的,还是不同的?如果它们不同,它们的区别是什么?

Ely*_*lye 6

根据我跟踪的代码,lifecycleScope将自动关闭ON_DESTROY

所以我从lifecycleScope-> getOrCreateAndroidScope()-> createAndBindAndroidScope-> bindScope(scope)->lifecycle.addObserver(ScopeObserver(event, this, scope))

代码如下所示。

val LifecycleOwner.lifecycleScope: Scope
    get() = getOrCreateAndroidScope()
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
fun LifecycleOwner.bindScope(scope: Scope, event: Lifecycle.Event = Lifecycle.Event.ON_DESTROY) {
    lifecycle.addObserver(ScopeObserver(event, this, scope))
}
Run Code Online (Sandbox Code Playgroud)
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()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)