我正在尝试注入一个在可组合项内的 hiltmodule 中定义的单例类。
我知道如何注入视图模型,但是单例类呢?
@Inject
lateinit var mysingleton: MySingletonClass
该代码在活动中运行良好,但将其从活动转移到使用它的可组合项还有很长的路要走......
有更好的解决办法吗?
您不应该将依赖项注入到函数中,这就是@可组合 https://developer.android.com/reference/kotlin/androidx/compose/runtime/Composable是。您可能希望将它们注入到 ViewModel 或 Activity 中。
如果您需要访问 @Composable 内的 ViewModel 范围(或应用程序范围)单例,则可以将该单例注入到 ViewModel 中,然后从 @Composable 访问 ViewModel。
您可以通过在 ViewModel hilt 模块中将该对象的提供程序函数注释为 @ViewScoped 来将该单例注入到 ViewModel 中。
如果您想要整个应用程序使用单例,而不是每个 ViewModel 实例使用单例,您可以将提供程序安装到 SingletonComponent::class 中并将其注释为 @Singleton。更多信息here https://developer.android.com/training/dependency-injection/hilt-android#component-scopes.
希尔特模块文件
@Module
@InstallIn(ViewModelComponent::class)
object ViewModelModule {
@ViewScoped
@Provides
fun provideMySingleton(): MySingletonClass = MySingletonClass()
}
您的 ViewModel 类:
@HiltViewModel
class MyViewModel
@Inject constructor(
val mySingleton: MySingletonClass
): ViewModel() {
...
}
您的 @Composable 函数:
@Composable fun DisplayPrettyScreen() {
...
val viewModel: MyViewModel = hiltViewModel()
val singleton = viewModel.mySingleton //no need to assign it to a local variable, just for explanation purposes
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)