简体   繁体   中英

Injecting dependencies in a Android ViewModel?

Hi i have a ViewModel that has two var's that get injected using Dagger 2.11.

However it never gets injected in my viewModel whilst everywhere else in my app, these same dependecy Vars get initialised and injected perfectly

Below is my viewModel

class MyViewModel : AndroidViewModel, MyViewModelContract {


    private lateinit var pointsBalance: MutableLiveData<PointsBalance>


    @Inject
    lateinit var accountDelegator: AccountDelegatorContract



@Inject
constructor(application: Application) : super(application)

init {
    DaggerApplicationComponent.builder().application(getApplication() as MyApplication).build().inject(this)
}

    override fun getPointsBalance(): LiveData<PointsBalance> {
        if (!this::pointsBalance.isInitialized) {
           //get balance from network api etc
        }

        return pointsBalance
    }

accountDelegator complains that it is not initialised

Below is how i bind this viewModel inside MyModule.class

   @Provides
    @JvmStatic
    @Singleton
    fun providesViewModel(viewModel: MyViewModel): MyViewModelContract = viewModel

my custom application

class MyApplication : DaggerApplication() {
    override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
        val applicationComponent = DaggerApplicationComponent.builder()
                .application(this)
                .build()
        applicationComponent.inject(this)
        return applicationComponent
    }

}

my applicationComponent

@Singleton
@Component(modules = arrayOf(MyModule::class,
        ))
interface ApplicationComponent : AndroidInjector<DaggerApplication> {
    fun inject(mApplication: MyApplication)
    override fun inject(instance: DaggerApplication)

    @Component.Builder
    interface Builder {
        @BindsInstance
        fun application(applicaton: MyApplication): Builder
        fun build(): ApplicationComponent
    }


}

How i use this viewmodel in a activity/fragment

viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)

I believe issue is that you're not calling inject . You'd need for a start to add following to ApplicationComponent

void inject(MyViewModel viewModel);

What I'm doing here then fwiw is inheriting from AndroidViewModel (which gives access to application instance) then calling following in ViewModel class (you'd need to substitute DaggerProvider.getComponent with however you're accessing component in your code)

init {
    DaggerProvider.getComponent(application).inject(this)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM