5

I'm learning Koin's Scope from https://github.com/InsertKoinIO/koin/blob/master/koin-projects/docs/reference/koin-android/scope.md

If I have a Koin module as below

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

In my activity, I could do this

class MyActivity : AppCompatActivity() {

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

Or I could use this.scope where this is MyActivity object.

class MyActivity : AppCompatActivity() {

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

I tested they are the same. Are both the same, or different? If they are different, what are their differences?

Elye
  • 53,639
  • 54
  • 212
  • 474

1 Answers1

9

Based on the code I traced, the lifecycleScope will automatically close upon ON_DESTROY

So I trace from the lifecycleScope -> getOrCreateAndroidScope() -> createAndBindAndroidScope -> bindScope(scope) -> lifecycle.addObserver(ScopeObserver(event, this, scope))

The codes are all shown below.

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()
        }
    }
}
Elye
  • 53,639
  • 54
  • 212
  • 474