在Android ViewModel中注入依赖项?

时间:2018-02-20 13:10:53

标签: android dagger-2 android-viewmodel

我有一个ViewModel有两个使用Dagger 2.11注入的var。

然而,在我的应用程序中的其他地方,它永远不会被注入我的viewModel中,这些相同的依赖Vars会被初始化并完美地注入

以下是我的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抱怨它未初始化

下面是我如何在MyModule.class

中绑定此viewModel
   @Provides
    @JvmStatic
    @Singleton
    fun providesViewModel(viewModel: MyViewModel): MyViewModelContract = viewModel

我的自定义应用

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

}

我的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
    }


}

我如何在activity / fragment中使用此viewmodel

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

1 个答案:

答案 0 :(得分:1)

我认为问题是你没有打电话给xn=1/(np.sqrt(1+np.exp(2(x0)**2))) 。您需要开始在inject

添加以下内容
ApplicationComponent

我在这里做的是fwiw继承自void inject(MyViewModel viewModel); (提供对应用程序实例的访问权限),然后在ViewModel类中调用以下内容(您需要用AndroidViewModel替换DaggerProvider.getComponent但是你正在访问代码中的组件

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