0

https://github.com/InsertKoinIO/koin/blob/master/koin-projects/docs/reference/koin-android/scope.md#sharing-instances-between-components-with-scopes中显示了以下示例

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

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

但我什至不知道如何获得presenter

我试试

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

但这不是正确的。如何得到我的presenter

4

1 回答 1

1

跟踪代码后,方法是使用parameter传递scopeId

对于上面的例子,它将是

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

如果有限定符,我们也只需要通过它们发送

scopeId下面的一个示例,我们需要通过 lambda和name限定符的参数发送。(参数可以通过任何类型的参数自定义)。

    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)))
        }
    }

然后调用就像下面这样简单

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

或者我们也可以

val nameScope = getKoin().createScope("SomeName", named("AScopeName"))
val environment = get<Environment>(parameters = { parametersOf("SomeName", "scopedName") })
于 2020-04-22T13:07:54.823 回答