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

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

问题描述

我正在尝试在 https://developer.android.com/jetpack 上实施示例/文档/指南.这解释了 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

我发现这个错误与此有关

I could figure out that this error has something to do with

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,

假设您有一个如下所示的视图模型类,

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.java)) {
        return SampleViewModel(dataManager) as T
    }
    throw IllegalStateException()
}

}

现在在你的模块类中,你可以注入上面的类,如下所示,(注意-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]
}

在你的片段中不,你可以像任何其他依赖一样注入你的视图模型,

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

@Injetct
lateinit viewModel:SampleViewModel

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

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