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?