Answer the question
In order to leave comments, you need to log in
How to inject interface implementations with Dagger2?
Good evening. Thought I googled but couldn't find the answer to my question. Can you suggest how to inject the implementation of the interface using dagger 2. There is a SavedListInteractor that has implementations of FavoritedListImpl, IgnoredListImpl. For example, I have 1 fragment with a view model, which is created using a factory that provides a SavedListInteractor and, depending on the value in the fragment argument (1 or 0), should assign the FavoritedListImpl or IgnoredListImpl instance I need. No matter how much I googled, I couldn't find an answer. I only got as far as creating several components for a fragment ... or 1 component containing 3 implementations.
Answer the question
In order to leave comments, you need to log in
Make a method in the component builder (the name is not important)
@BindsInstance
fun bindInteractor(interactor: SavedListInteractor): Builder
@Qualifier
annotation class MyFlag
@Component(modules = [InteractorModule::class])
interface MyComponent {
@Component.Builder
interface Builder {
@BindsInstance
fun bindMyFlag(@MyFlag flag: Int): Builder
fun build(): MyComponent
}
...
}
@Module
object InteractorModule {
@Provides
fun provideInteractor(@MyFlag flag: Int, impl0: Provider< FavoritedListImpl>, impl1: Provider< IgnoredListImpl>): SavedListInteractor = when (flag) {
0 -> impl0.get()
1 -> impl1.get()
else -> throw IllegalArgumentExcepion("Unknown flag: $flag")
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question