2

I'm trying to pass location data from one fragment to a ViewModel which updates my UI.

I have a fragment which contains a MapBoxCoordinatesListener. Every time, when the location is changed, I want to display the updated coordinates to the user. The labels to do this are on the another layout and I can access them via MainActivity's ViewModel.

MainActivity:

override fun onCreate(savedInstanceState: Bundle?) {

        (...)

        showMapFragment()

        initMainMenuBinding(activityMainBinding)
}

private fun initMainMenuBinding(activityMainBinding: ActivityMainBinding) {
        mainMenuViewModel = MainMenuViewModel()
        mainMenuViewModel.mainButtonsCallback = object : MainMenuViewModel.MainButtonsCallback {

            (..)

        }
        activityMainBinding.mainMenu.viewModel = mainMenuViewModel
    }

private fun showMapFragment() {
         mapFragment = supportFragmentManager.findFragmentByTag(MapFragment.TAG)
                ?: MapFragment.newInstance()

        val fragmentTransaction = supportFragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.map_container, mapFragment, MapFragment.TAG)
        fragmentTransaction.commit()
    }
MainMenuViewModel:
class MainMenuViewModel : BaseObservable(){
    lateinit var mainButtonsCallback: MainButtonsCallback

    (...)

    @get:Bindable
    var latLangModel = LatLangModel("latitude", "longitude")
}

I was thinking about sending coordinates from MapFragment to activity with a callback, but then I don't know how to pass data to ViewModel. Also I have doubts if this is a robust solution to archive what I want.

How can I achieve this in a robust way?

kerutf
  • 41
  • 1
  • 6
  • 1
    Refer Shared ViewModel: https://developer.android.com/topic/libraries/architecture/viewmodel#sharing from android docs – Abhimanyu May 12 '19 at 12:21
  • @Abhi thanks, using the LiveData is a good idea. But how access to that LiveData from the ViewModel layer? – kerutf May 13 '19 at 11:34
  • I still use Java for all my projects So I cannot provide any code. You can check android developer docs for using ViewModel to communication between activity to fragment and fragment to fragment. – Abhimanyu May 13 '19 at 17:21
  • @Abhi I'm familiar with JAVA, so it does not a problem for me. – kerutf May 13 '19 at 22:33
  • @Abhi What I don't understand is how to pass value to ViewModel layer ( place where I bind all views). I get value from a one fragment and how should I tell to the other Fragment's/Activity's ViewModel that it should update UI? – kerutf May 13 '19 at 22:40

0 Answers0