Building an Android Instant App with Application Component from Dagger

后端 未结 2 938
臣服心动
臣服心动 2021-02-12 11:36

I\'m currently experimenting with InstantApps and would like to include dagger into my project.

I\'m facing an issue setting up an application AppComponent. My applicati

2条回答
  •  无人共我
    2021-02-12 11:55

    I wrote an article about this with many details: Dagger2 for Modular Architecture, but following the short answer.

    You have to use Dagger2 in a different way. Instead of using a module or subcomponent for each feature module, you need to use a component with a dependency to the base AppComponent.

    In a single module we are usually do something like this:

    @Singleton
    @Component(modules = arrayOf(NetworkModule::class, RepositoryModule::class, 
                         SubcomponentModule::class))
    interface ApplicationComponent : AndroidInjector {
      val userRepository: UserRepository
      val apiService: ApiService
    }
    
    @Module
    object NetworkModule {
      @Provides
      @Singleton
      @JvmStatic
      fun provideApiService(okHttp: OkHttp): ApiService {
        return ApiSerive(okHttp)
      }
     }
    

    But as you said you don't have access to SubComponentModule that could be in another module or reference dagger modules in another feature module.

    You can just create a new dagger module in a feature module depending on ApplicationComponent like this:

    @Browser
    @Component(modules = [(BrowserModule::class)],
          dependencies = [(AppComponent::class)])
    interface BrowserComponent : AndroidInjector {
      @Component.Builder
      abstract class Builder: AndroidInjector.Builder(){
        /**
        *  explicity declare to Dagger2
        * that this builder will accept an AppComponent instance
        **/
        abstract fun plus(component: AppComponent): Builder
      }
    }
    

    And the corresponding feature activity will build the component:

    class BrowserActivity : AppCompatActivity() {
      override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DaggerBrowserComponent
            .builder()
            /**
             * we have to provide an instance of the AppComponent or
             * any other dependency for this component
             **/
            .plus((application as MyApplication).component)
            .build()
            .inject(this)
      }
    }
    

提交回复
热议问题