E
E
Eugene2019-06-03 21:30:11
Android
Eugene, 2019-06-03 21:30:11

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

1 answer(s)
D
Denis Zagaevsky, 2019-06-03
@evgdev

Make a method in the component builder (the name is not important)

@BindsInstance
fun bindInteractor(interactor: SavedListInteractor): Builder

when you create a component in a fragment, you will call this method
https://dagger.dev/api/2.10/dagger/BindsInstance.html
You can also do something like this:
@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")
    }
}

That is, we put an annotated flag into the graph, which comes in the arguments (you can do without the annotation, but the gods of the dagger will punish - worse than an unnamed int in the graph, only an unnamed int in the event bus. Not comme il faut, in short). Then, using this flag, we lazily sort out which implementation to give

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question