Reputation: 123
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
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
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