1

我有一个范围

scope<MyObject> {
    scoped { Presenter() }
}

然后当我得到演示者时,这有效。

val presenter = myObject.scope.get<Presenter>(Presenter::class.java)

同样,当我可以分配一个范围变量时,然后获取演示者。

val myScope = myObject.scope
val presenter = myScope.get<Presenter>(Presenter::class.java)

如果我们关闭它,这仍然可以

val presenter = myObject.scope.get<Presenter>(Presenter::class.java)
myObject.scope.close()
val presenter2 = myObject.scope.get<Presenter>(Presenter::class.java)

但是,如果我分配给另一个范围变量并关闭它,它将失败。

val myScope = myObject.scope
val presenter = myScope.get<Presenter>(Presenter::class.java)
myScope.close()
val presenter2 = myScope.get<Presenter>(Presenter::class.java) // Crash here.

同样,如果我这样做,它也会崩溃

val myScope = myObject.scope
val presenter = myScope.get<Presenter>(Presenter::class.java)
myScope.close()
myScope.getOrCreateScope() // Crash here
val presenter2 = myScope.get<Presenter>(Presenter::class.java)

我明白了close(),范围不能再提供presenter了。我就是不明白为什么之后myObject.scope.close()myObject.scope还能提供presenter?(和同一个主持人)

val presenter = myObject.scope.get<Presenter>(Presenter::class.java)
myObject.scope.close()
val presenter2 = myObject.scope.get<Presenter>(Presenter::class.java) 
// presenter1 == presenter2
4

1 回答 1

0

显然,myObject.scope实际上是myObject.getOrCreateScope()。因此,即使在myObject.scope.close()被调用之后,myObject.scope它仍然会工作,因为它会再次创建一个新的范围。

但是如果我们执行以下操作(关闭它),无论使用myScopeor myObject.scope,它仍然会关闭,因此再次使用它myScope会崩溃。

val myScope = myObject.scope
val presenter = myScope.get<Presenter>(Presenter::class.java)
myObject.scope.close() // or myScope.scope
val presenter2 = myScope.get<Presenter>(Presenter::class.java) // this will crash

请参阅下面的讨论并找到 https://github.com/InsertKoinIO/koin/issues/786

于 2020-04-23T11:35:05.303 回答