【问题标题】:Koin's lifecycleScope vs activity.scope. Are they the same?Koin 的生命周期范围与活动范围。他们是一样的吗?
【发布时间】:2020-04-20 08:14:19
【问题描述】:

我正在向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.scope,其中thisMyActivity 对象。

class MyActivity : AppCompatActivity() {

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

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

【问题讨论】:

    标签: android kotlin android-lifecycle koin koin-scope


    【解决方案1】:

    根据我跟踪的代码,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()
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多