简体   繁体   English

ShareViewModel 如何在可组合函数中获得单例

[英]ShareViewModel how to get a singleton in composable function

I have a hybrid app, I need a singleton of the Shared ViewModel class, in my composable function.我有一个混合应用程序,我需要在我的可组合函数中使用 Shared ViewModel 类的单例。 I use Hilt.我用希尔特。

my SahreViewModel class:我的 SahreViewModel 类:

class SharedViewModel : ViewModel() { ... }

I use my SharedViewModel everywhere in my app, and can get the singleton it in any fragment as:我在我的应用程序中随处使用我的 SharedViewModel,并且可以在任何片段中获取单例:

private val sharedViewModel: SharedViewModel by activityViewModels()

Same I would like to get in the composable function.同样,我想进入可组合函数。

I find two workarounds for this我找到了两个解决方法

  1. As you said you can fetch the singleton view model by activityViewModels() then you could simply pass it to the composable function.正如您所说,您可以by activityViewModels()获取单例视图模型,然后您可以简单地将它传递给可组合函数。 I imagine one needs the ViewModel inside his top-level composable functions only to make the lower-level reusable, so this solution makes much sense to me.我想一个人需要在他的顶级可组合函数中使用 ViewModel 只是为了使较低级别的可重用,所以这个解决方案对我来说很有意义。
  2. You can simply create another class containing all the logic that you want to be singleton and annotate with @Singleton and inject it to the ViewModel and by that, although you will have different ViewModel objects, the shared logic will be of the same object across the application.您可以简单地创建另一个类,其中包含您希望成为单例的所有逻辑,并使用@Singleton进行注释并将其注入 ViewModel,这样,尽管您将拥有不同的 ViewModel 对象,但共享逻辑将是同一对象应用。
val sharedViewModel: SharedViewModel = viewModel()

viewModel() returns an existing ViewModel or creates a new one in the given scope. viewModel()返回一个现有的 ViewModel 或在给定范围内创建一个新的 ViewModel。 The ViewModel is retained as long as the scope is alive.只要范围处于活动状态,就会保留 ViewModel。 For example, if the composable is used in an activity, viewModel() returns the same instance until the activity is finished or the process is killed.例如,如果在活动中使用可组合项,则viewModel()返回相同的实例,直到活动完成或进程被终止。

The viewModel() function automatically uses the ViewModel that Hilt constructs with the @HiltViewModel annotation. viewModel()函数自动使用 Hilt 使用@HiltViewModel注释构造的 ViewModel。

Due to their lifecycle and scoping, you should access and call ViewModel instances at screen-level composables, that is, close to a root composable called from an activity, fragment, or destination of a Navigation graph.由于它们的生命周期和范围界定,您应该在屏幕级可组合项访问和调用 ViewModel 实例,也就是说,靠近从导航图的活动、片段或目的地调用的根可组合项。 You should never pass down ViewModel instances to other composables, pass only the data they need and functions that perform the required logic as parameters.您永远不应该将 ViewModel 实例传递给其他可组合项,只传递它们需要的数据和执行所需逻辑的函数作为参数。

Link 关联

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM