Reputation: 6126
I have a Util module as below, it requires the activity context [not application context] to do some of its functions.
How do I inject the activity context into it?
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
Upvotes: 2
Views: 8590
Reputation: 883
You can append activity/fragment instance dynamic into scope instance registry with koin lifecycle extensions.
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
Then inject it in scope defination:
scope<SomeActivity> {
// inject activity with Scope.get()
scoped { SomeModule(get()) }
}
Finally, inject with lifecycleScope:
val someModule: SomeModule by lifecycleScope.inject()
I wrote a demo to explain how it works: https://github.com/twiceyuan/KoinAndroidComponentInject
Upvotes: 0
Reputation: 3309
In this case, as @commonsware said, it's not good that the presenter class depends on the activity. The better solution with the injection can be like the following the structure:
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)
Your module:
single { MainPresenter( it[0], it[1] ) }
Upvotes: 6