Bind Fragment/Activity to MVP View contract with Dagger Hilt

Viewed 1281

I am currently trying to migrate from dagger-android to Hilt. Previously I used @Bind to bind instances of fragments and activities to the corresponding MVP View contract. Is there a way to do the same with Hilt? It doesn't seem to be able to inject sepcific fragments and activities?

1 Answers

We need some code to give a proper answer, but I think you need something like

@InstallIn(ActivityComponent::class)
@Module
abstract class MyScreenModule {

    @ActivityScoped
    @Binds
    abstract fun bindMyScreenFragment(impl: ScreenFragment): MyScreenContract.View


    @ActivityScoped
    @Binds
    abstract fun bindMyScreenPresenter(impl: ScreenPresenter): MyScreenContract.Presenter

}

Don't forget:

  • Add '@Inject' to the Fragment and Presenter constructors
  • Add @AndroidEntryPoint to MyScreenActivity and MyScreenFragment

NOTE: Consider if the Presenter should be bounded to the Fragment lifecycle. In this case, the presenter binding should have it's own module marked with @InstallIn(FragmentComponent::class) and the binding scoped to @FragmentScoped

Related