如何使用依赖项注入在ViewModel中注入构造函数 [英] How to use dependency injection for injecting constructor in a ViewModel

本文介绍了如何使用依赖项注入在ViewModel中注入构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 https://developer.android.com/jetpack上实现该示例/docs/guide .这说明了tan android应用的结构.

I am trying to implement the example on https://developer.android.com/jetpack/docs/guide. This explains how tan android app should be structured.

当我使用相同的代码时,出现以下错误.

When I use the same code, I get following error.

java.lang.Class<com.example.UserProfileViewModel> has no zero argument constructor

我发现这个错误与

viewModel = ViewModelProviders.of(this).get(UserProfileViewModel.class);


当我为ViewModel编写默认的零输入构造函数时,出现以下错误.


When I write a default zero input constructor for ViewModel I get the following error.

Attempt to invoke virtual method 'void android.arch.lifecycle.LiveData.observe(android.arch.lifecycle.LifecycleOwner, android.arch.lifecycle.Observer)' on a null object reference

我不知道此错误的原因以及解决方法.

I can not figure out the reason for this error and how to solve it.

推荐答案

如果要在Fragment中为viewmodel提供构造函数作为依赖项,则可以使用另一种方法,

If you want to provide viewmodel with constructor as a dependency in your Fragment, there is a different method for it,

假设您有一个如下的viewmodel类,

Lets suppose you have a viewmodel class as belows,

class SampleViewmModel(dataManager:DataManager):ViewModel(){
  //some logic
}

然后,您需要创建一个工厂类来支持如下所示的viewmodel,

Then you will need to create a factory class to support above viewmodel like below,

class SampleFactory @Inject constructor(var dataManager:DataManager): ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
    if (modelClass.isAssignableFrom(SampleViewModel::class)) {
        return SampleViewModel(dataManager) as T
    }
    throw IllegalStateException()
}

}

现在在您的模块类中,您可以按以下方式注入以上类,(Note-Datamanager类是可注入的)

Now in your module class, you can inject above classes as below, (Note-Datamanager class is injectible)

//Provide Factory
@Provides
fun provideFactory(dataManager:DataManager): SampleFactory {
    return SampleFactory(dataManager)
}

//Provide actual viewmodel
@Provides
fun provideViewModel(sampleFactory: SampleFactory): SampleViewModel {
    return ViewModelProviders.of(fragment, sampleFactory)[SampleViewModel::class]
}

否,在您的Fragment中,您可以像其他任何依赖项一样注入viewmodel,

No in your Fragment, you can inject your viewmodel just like any other dependency,

@Injetct
lateinit viewModel:SampleViewModel

这篇关于如何使用依赖项注入在ViewModel中注入构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆