Android Multi Module and Hilt Issue

682 views Asked by At

We have an multi module Android project which has following modules:

  1. Common module
  2. Library module A
  3. Library module B

The Common module needs some dependencies of Type A and Type B for its features. These are common dependencies that can be provided by Library A and Library B using Hilt. Below is the code snippet that uses these dependencies in the common module:

class CommonFeature {

      @Inject lateinit var a: A
      @Inject lateinit var b: B

      fun doSomething() {
          a.doSomething()
          b.doSomething()
      }

  }

When we build the application with Library A and the common module, the Dependency A and the Dependency B are provided by the Library A.

@Module
@InstallIn(SingletonComponent::class)
class LibraryAModule {

    @Provides
    @Singleton
    fun providesDependencyA(): A = DependencyAImpl()

    @Provides
    @Singleton
    fun providesDependencyB(): B = DependencyBImpl()
}

Similarly, when we build the application with Library B and the common module, the dependencies are provided by Library B.

@Module
@InstallIn(SingletonComponent::class)
class LibraryBModule {

    @Provides
    @Singleton
    fun providesDependencyA(): A = DependencyAImpl()

    @Provides
    @Singleton
    fun providesDependencyB(): B = DependencyBImpl()
}

However, we have a requirement where we have to build the application using Library A, Library B and the common module. When this app starts, it decides which library should it use depending on some factors.

But, in this case, Hilt fails at compile time because it gets confused as suppose to which dependency should it provide when the common module asks for a dependency. For example, when the common module asks for Dependency A, it has two sources from which it can provide it i.e. Library A and Library B. Hence, it gets confused.

We researched a bit about providing modules at run-time, but even that's not possible. The research includes following question:

How can i pass runtime dependepcy to Hilt module?

https://developer.android.com/training/dependency-injection/hilt-android#multiple-bindings

We are aware that we can provide multiple binding of same type in hilt but that requires qualifiers. But we can't hard code qualifiers in our common module.

Can anyone help us with the workaround to achieve what we are trying to achieve?

0

There are 0 answers