4

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

如果我有如下 Koin 模块

val myModule =
    module {
        scope<MyActivity> { scoped { Presenter() } }
    }

在我的活动中,我可以这样做

class MyActivity : AppCompatActivity() {

    private val presenter by lazy {
        lifecycleScope.get<Presenter>(Presenter::class.java)
    }
    // ...
}

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

class MyActivity : AppCompatActivity() {

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

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

4

1 回答 1

6

根据我跟踪的代码,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()
        }
    }
}
于 2020-04-20T09:52:22.807 回答