首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >HILT :在ViewModel中还没有初始化延迟属性存储库

HILT :在ViewModel中还没有初始化延迟属性存储库
EN

Stack Overflow用户
提问于 2020-07-10 02:57:55
回答 6查看 12K关注 0票数 12

我正面临这个问题,在多模块android项目与刀柄。

代码语言:javascript
运行
复制
 kotlin.UninitializedPropertyAccessException: lateinit property repository has not been initialized in MyViewModel

我的模块是

Module

  • Viewmodel Module

  • DataSource
  1. 应用程序模块
  2. UseCase

‘应用模块’

代码语言:javascript
运行
复制
@AndroidEntryPoint
class MainFragment : Fragment() {
private lateinit var viewModel: MainViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View {
    return inflater.inflate(R.layout.main_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
    viewModel.test()
}}

'ViewModel模块‘

代码语言:javascript
运行
复制
class MainViewModel @ViewModelInject constructor(private val repository: MyUsecase): ViewModel() {
fun test(){
    repository.test()
}}

'UseCase模块‘

代码语言:javascript
运行
复制
class MyUsecase @Inject constructor() {

@Inject
lateinit var feature: Feature

fun doThing() {
    feature.doThing()
}

@Module
@InstallIn(ApplicationComponent::class)
object FeatureModule {
    @Provides
    fun feature(realFeature: RealFeature): Feature = realFeature
}
}

'DataSource模块‘

代码语言:javascript
运行
复制
interface Feature {
fun doThing()
}

class RealFeature : Feature {
override fun doThing() {
    Log.v("Feature", "Doing the thing!")
}
}

依赖关系是

MyFragment

我对这段代码做错了什么请改正。

EN

Stack Overflow用户

发布于 2020-07-29 13:49:54

首先,我认为在您的@Inject类中缺少了RealFeature,因此Hilt知道如何注入依赖项。其次,如果您想要注入一个不属于Hilt支持的入口点的类,则需要为该类定义自己的入口点。

除了用@Provides方法编写的模块之外,还需要告诉Hilt如何访问依赖项。

在您的情况下,您应该尝试这样的方法:

代码语言:javascript
运行
复制
@EntryPoint
@InstallIn(ApplicationComponent::class)
interface FeatureInterface {
    fun getFeatureClass(): Feature
}

然后,当您想使用它时,编写如下内容:

代码语言:javascript
运行
复制
        val featureInterface =
        EntryPoints.get(appContext, FeatureInterface::class.java)
        val realFeature = featureInterface.getFeatureClass()

您可以在这里找到更多信息:

https://dagger.dev/hilt/entry-points

https://developer.android.com/training/dependency-injection/hilt-android#not-supported

票数 0
EN
查看全部 6 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62826677

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档