将子组件实例添加到活动中

时间:2017-03-12 19:52:48

标签: android kotlin dagger-2

AppModule

@Module(subcomponents = arrayOf(ActivityComponent::class))
class AppModule(private val context: Context) {

  @Provides @PerApplication
  fun provideContext() = context

  @Provides @PerApplication
  fun provideSharedPreferences(context: Context)
      = context.getSharedPreferences("${context.packageName}.preferences", Context.MODE_PRIVATE)

  @Provides @PerApplication
  fun provideMoshi() = Moshi.Builder().build()

  @Provides @PerApplication
  fun provideRetrofit(moshi: Moshi): Retrofit {
    return Retrofit.Builder()
        .baseUrl("https://reqres.in")
        .addConverterFactory(MoshiConverterFactory.create(moshi))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
        .build()
  }
}

ActivityComponent

@PerActivity
@Subcomponent(modules = arrayOf(ActivityModule::class))
interface ActivityComponent {

  fun inject(activity: MainActivity)

  @Subcomponent.Builder
  interface Builder {
    fun activityModule(module: ActivityModule): Builder
    fun build(): ActivityComponent
  }
}

ActivityModule

@Module
class ActivityModule(private val activity: FragmentActivity) {

  @Provides @PerActivity
  fun provideActivity() = activity

  @Provides @PerActivity
  fun provideTestApi(retrofit: Retrofit) = retrofit.create(TestApi::class.java)
}

ActivityComponent

MainActivity

如何将AppComponent的Builder实例导入fun activityComponent(module: ActivityModule): ActivityComponent

活动由Dagger创建,因此我不能像enter image description here中给出的示例那样将提供者注入构造函数。

我尝试使用pre dagger-2.7创建子组件的方法,将以下行添加到MainActivity

(application as App).appComponent.activityComponent(ActivityModule(this)).inject(this)

和{{1}}:

{{1}}

给了我:

  

错误:[com.example.injection.ActivityComponent.inject(com.example.modules.main.MainActivity)]如果没有@ Provide-annotated方法,则无法提供com.example.api.TestApi。

0 个答案:

没有答案