Jujare Vinayak
Jujare Vinayak

Reputation: 123

How to use same instance of ViewModel in activity as well as fragment?

I have created an instance of ViewModel in MainActivity and setup an observer. I want the observed data into one of the fragments of MainActivity's ViewPager. How can I get the required LiveData into the fragment.

Upvotes: 0

Views: 765

Answers (2)

Wilson Tran
Wilson Tran

Reputation: 4831

Using AndroidX extension delegate

In the MainActivity:

private val activityViewModel: SomeViewModel by viewModels()

In the Fragement

private val activityViewModel: SomeViewModel by activityViewModels()

With ViewModelFactory, put the ViewModelFactory intance into closure

private val activityViewModel: SomeViewModel by viewModels{ viewModelFactory }
private val activityViewModel: SomeViewModel by activityViewModels{ viewModelFactory}

Upvotes: 3

Mhmd
Mhmd

Reputation: 111

you can use shared ViewModel Shared ViewModel between activity and fragments

for this you can define an object from activity's viewModel in your fragment with activity as viewModel's owner and apply changes on that's variables.

Upvotes: 0

Related Questions