gpt4 book ai didi

android - Koin 的生命周期范围与 Activity 范围。他们是一样的吗?

转载 作者:行者123 更新时间:2023-12-02 12:37:26 30 4
gpt4 key购买 nike

我正在从 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() } }
}

在我的 Activity 中,我可以这样做
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)
}
// ...
}

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

最佳答案

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

关于android - Koin 的生命周期范围与 Activity 范围。他们是一样的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61317876/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com