Search code examples
kotlinservice-locatorkoinkoin-scope

Koin: Why after myObject.scope.close(), it still works?


I have a scope

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

Then when I get presenter, this works.

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

Similarly, when I can assign a scope variable, then get the presenter.

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

If we close it, this is still okay

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

However if I assign to another scope variable, and close it, it will fail.

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

Similarly, if I do this, it will crash too

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)

I understand after close(), the scope can't get to provide the presenter anymore. I just don't understand why after myObject.scope.close(), myObject.scope still can provide presenter? (and the same presenter)

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

Solution

  • Apparently, myObject.scope is actually myObject.getOrCreateScope(). Hence even after myObject.scope.close() is called, myObject.scope will still work as it will create a new scope again.

    But if we do the below (closing it), regardless of using myScope or myObject.scope, it will still close, and hence use it again from myScope will crash.

    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
    

    Refer to the below for the discussion and finding https://github.com/InsertKoinIO/koin/issues/786