Elye
Elye

Reputation: 60241

How to inject scopeId into Koin to get the dependency?

In https://github.com/InsertKoinIO/koin/blob/master/koin-projects/docs/reference/koin-android/scope.md#sharing-instances-between-components-with-scopes it is shown the below example

module {
    // Shared user session data
    scope(named("session")) {
        scoped { UserSession() }
    }

    // Inject UserSession instance from "session" Scope
    factory { (scopeId : ScopeID) -> Presenter(getScope(scopeId).get())}
}

But I don't even know how to get presenter?

I try

val nameScope = getKoin().createScope("SomeName", named("session"))
val presenter = get<Presenter>(nameScope.id)

but it's not the correct. How to get my presenter?

Upvotes: 0

Views: 2557

Answers (1)

Elye
Elye

Reputation: 60241

After tracing the code, the way to do it is to use parameter to pass over the scopeId

For the above example, it will be

val nameScope = getKoin().createScope("SomeName", named("session"))
val presenter = get<Presenter>(parameters = { parametersOf(nameScope.id) )

If there's qualifier, we just need to send through them as well

One Example as below where we need a parameter of the lambda to send through scopeId and name of the qualifier. (the argument is self definable through the parameters of any type).

    module {
        scope(named("AScopeName")) {
            scoped(qualifier = named("scopedName")) { Dependency() }
            factory(qualifier = named("factoryName")) { Dependency() }
        }


        factory { (scopeId: ScopeID, name: String) ->
            Environment(getScope(scopeId).get(qualifier = named(name)))
        }
    }

Then the calling is as simple as below

val nameScope = getKoin().createScope("SomeName", named("AScopeName"))
val environment = get<Environment>(parameters = { parametersOf(nameScope.id, "scopedName") })

Or we could also

val nameScope = getKoin().createScope("SomeName", named("AScopeName"))
val environment = get<Environment>(parameters = { parametersOf("SomeName", "scopedName") })

Upvotes: 1

Related Questions