What is the use case for @Binds vs @Provides annotation in Dagger2

前端 未结 2 1833
长发绾君心
长发绾君心 2020-12-15 04:45

I am not certain on the purpose for Dagger2\'s @Bind annotation.

From what i have read online im still not clear but here is an example:

@Module
pu         


        
2条回答
  •  忘掉有多难
    2020-12-15 05:04

    Here a concrete case where you need Bind annotation, imagine you got a BaseActivityModule which is include in all your activity modules that provides your activity viewmodel.

    @Module
    object BaseActivityModule {
        @Provides
        @ActivityScope
        @ActivityContext
        @JvmStatic
        fun provideViewModelProvider(
            activity: AppCompatActivity,
            viewModelFactory: ViewModelProvider.Factory
        ): ViewModelProvider = ViewModelProviders.of(activity, viewModelFactory)
    }
    

    Here you see we need to provide an AppCompatActivity and a ViewModelProvider.Factory. You cannot provide AppCompatActivity with a Provide annotation since activities are created by android.

    We're assuming your concrete ActivityModule for example MainActivityModule will provide MainActivity class either because you create a MainActivity sub component or you used ContributesAndroidInjector to automatically create your sub components (but this is another talk).

    So we have our MainActivityModule providing MainActivity and our MainActivityModule includes our BaseActivityModule which need an AppCompatActivity. So here the Bind magic, let's tell Dagger that when you need an AppCompatActivity you can use our MainActivity.

    @Module(includes = [BaseActivityModule::class])
    abstract class MainActivityModule {
        @Binds
        @ActivityScope
        abstract fun bindActivity(activity: MainActivity): AppCompatActivity
    }
    

    You can see more from my project template here

提交回复
热议问题