0

I've an host activity with 4 tabs, one fragment for each tab.

  • In the host activity I collect the user's location through FusedLocationProviderClient.

  • I want to pass that location to the child fragments.

It seems that I've to use a ViewModel like:

class LocationViewModel : ViewModel() {
    lateinit var location: Location
}

How can I inform the fragments when the location has been set by the host Activity? Thanks.

EDIT - Solution

Using MutableLiveData as suggested did the trick.

class LocationViewModel : ViewModel()
{
    private val mutableLiveLocation = MutableLiveData<Location>()
    val liveLocation: LiveData<Location> get() = mutableLiveLocation

    fun setLocation(location: Location)
    {
        mutableLiveLocation.value = location
    }
}
mik3.rizzo
  • 65
  • 7
  • 1
    You need to setup viewModel sharing between activity and fragments. Check out the answers here https://stackoverflow.com/questions/60885459/how-to-share-data-between-activity-and-fragment-via-viewmodel-class-in-android – MikkelT Jan 12 '23 at 22:50
  • 1
    Either send it directly through the supportFragmentManager by finding the fragment tag or use subscription model like LiveData – Zain Jan 12 '23 at 22:50
  • Thank you guys, with your help I solved and I also shared the solution. – mik3.rizzo Jan 12 '23 at 23:44

0 Answers0