0

I have a fragment. When I click a button I want to call the DB to get some data. I put that data in an observable live data. That data is displayed on the Activity. Can I observe the data inside my activity? So I want to call the method of my ViewModel inside my fragment and observe the MutableLiveData inside my activity. It is possible?

vaniokmd
  • 59
  • 7
  • 1
    Look at [Share data between fragments](https://developer.android.com/topic/libraries/architecture/viewmodel#sharing) – Onik Oct 27 '20 at 10:44

1 Answers1

1

Yes, it's absolutely possible. All you need to do is share your view model instance between activity & fragment.

How? using ViewModelProvider() in fragment, instead of passing this as owner, you need to pass activity instance from fragment. And if your fragment is already on same activity then it would give you view model instance of activity rather than creating new one.

Actual syntax on Fragment:

ViewModelProvider(requireActivity())[MyViewModel::class.java]

It's easy when using viewModel-ktx dependency like one of link in comments suggests.

Jeel Vankhede
  • 11,592
  • 2
  • 28
  • 58