Jono
Jono

Reputation: 18108

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)

Upvotes: 2

Views: 1577

Answers (1)

John O&#39;Reilly
John O&#39;Reilly

Reputation: 10330

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)
}

Upvotes: 1

Related Questions