Home > Software design >  ShareViewModel how to get a singleton in composable function
ShareViewModel how to get a singleton in composable function

Time:12-20

I have a hybrid app, I need a singleton of the Shared ViewModel class, in my composable function. I use Hilt.

my SahreViewModel class:

class SharedViewModel : ViewModel() { ... }

I use my SharedViewModel everywhere in my app, and can get the singleton it in any fragment as:

private val sharedViewModel: SharedViewModel by activityViewModels()

Same I would like to get in the composable function.

CodePudding user response:

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. 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.
  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.

CodePudding user response:

val sharedViewModel: SharedViewModel = viewModel()

viewModel() returns an existing ViewModel or creates a new one in the given scope. The ViewModel is retained as long as the scope is alive. 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.

The viewModel() function automatically uses the ViewModel that Hilt constructs with the @HiltViewModel annotation.

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. 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.

Link

  • Related