gpt4 book ai didi

android - 如何在 Kodein 或 Koin 中注入(inject) Activity 或 fragment 之外的依赖项?

转载 作者:行者123 更新时间:2023-11-29 02:23:03 47 4
gpt4 key购买 nike

想用 Kodein DI Android 在非 Activity 或 Fragment 类中初始化接口(interface)

示例仅显示在 activity 中使用 Kodein,但在其他部分没有显示

 class MainViewModel() :  KodeinAware{
override val kodein by closestKodein()
val repository : Repository by instance()
}

在 Activity 中有效,但在其他类中显示错误。我想在另一个类中初始化接口(interface)

最佳答案

closestKodein 仅适用于 Android Context 感知类(例如 fragment 和 Activity )。要在这些类之外使用它,您需要一个 Android context

android文档明确指出:

Caution: A ViewModel must never reference a view, Lifecycle, or any class that may hold a reference to the activity context.

[...]

If the ViewModel needs the Application context, for example to find a system service, it can extend the AndroidViewModel class and have a constructor that receives the Application in the constructor, since Application class extends Context.

因此,要从 ViewModel 访问 Kodein:

class MainViewModel(app: Application) : ApplicationViewModel(app), KodeinAware {
override val kodein = app.kodein
val repository : Repository by instance()
}

关于android - 如何在 Kodein 或 Koin 中注入(inject) Activity 或 fragment 之外的依赖项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54025957/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com