2

我有一个如下的 Util 模块,它需要活动上下文 [不是应用程序上下文] 来执行它的一些功能。

如何将活动上下文注入其中?

class MainPresenter internal constructor(private val iMainActivity: IActivity)  : IPresenter {

    //dependencies
    private val context = iMainActivity as AppCompatActivity

    private var util = UtilModule(context)         //<-- inject this
    private var httpClient = HttpClient(context)   //<-- inject this
4

2 回答 2

5

在这种情况下,正如@commonsware所说,presenter 类依赖于活动是不好的。注入的更好解决方案可以是以下结构:

class IActivity{

    private val utilModule: UtilModule by lazy { UtilModule(this@IActivity) }
    private val httpClient: HttpClient by lazy { HttpClient(this@IActivity) }

    private val presenter: MainPresenter by inject{ parametersOf(utilModel, 
    httpClient) }

}

class MainPresenter(private val util: UtilModule, private val httpClient: HttpClient)

你的模块:

single { MainPresenter( it[0], it[1] ) }
于 2019-05-26T01:45:58.287 回答
0

您可以使用 koin 生命周期扩展将活动/片段实例动态附加到范围实例注册表中。

val definition = BeanDefinition(
    scopeDefinition = this._scopeDefinition,
    primaryType = T::class,
    kind = Kind.Single,
    definition = { instance() }
)

val instanceMap = lifecycleScope._instanceRegistry.instances as HashMap<IndexKey, InstanceFactory<*>>
val factory = SingleInstanceFactory(this._koin, definition)
instanceMap[indexKey(T::class, null)] = factory

然后将其注入范围定义中:

scope<SomeActivity> {
    // inject activity with Scope.get()
    scoped { SomeModule(get()) }
}

最后,使用生命周期范围注入:

val someModule: SomeModule by lifecycleScope.inject()

我写了一个演示来解释它是如何工作的: https ://github.com/twiceyuan/KoinAndroidComponentInject

于 2020-04-11T15:51:08.793 回答