Difference between ActivityViewModels and lazy ViewModelProvider?

Viewed 9525

Difference between ActivityViewModels and lazy ViewModelProvider?

I've seen 2 ways to initialize a viewmodel:

private val someViewModel: SomeViewModel by activityViewModels()
private val someOtherViewModel: SomeOtherViewModel by lazy {
        ViewModelProvider(this).get(SomeOtherViewModel::class.java)
}

I know lazy initializes the ViewModel only when it's needed and that activityViewModels is useful for sharing data between fragments, but other than that what's the difference?

Android documentation says the activityViewModels is scoped to the activity, but does that mean if the same viewmodel is used in multiple fragments within the same activity using activityViewModels that there's only one instance created that's shared between all the fragments?

1 Answers

When you call ViewModelProvider(this), this refers to the ViewModelStoreOwner.

For each unique ViewModelStoreOwner, there will be a unique ViewModel of the given type.

Now coming to the question.

When you call

private val someOtherViewModel: SomeOtherViewModel by lazy {
  ViewModelProvider(this).get(SomeOtherViewModel::class.java)
}

you are getting a ViewModel that is scoped to the current Fragment/Activity. Lazy just defers the initialization.

When you call

private val someViewModel: SomeViewModel by activityViewModels()

you are getting a ViewModel that is scoped to the Activity. When multiple fragments use the same code, they are requesting ViewModels scoped to the parent Activity. If the parent Activity for all the Fragments is the same, the Fragments will get the same ViewModel since the ViewModelStoreOwner connected to the Activity remains the same.

Related