Avoid getting location twice

Viewed 25

I need location in a Jetpack Compose app with two viewmodels. Viewmodel_A gets the location but the location is also needed later in viewmodel_B. How can I pass the location from viewmodel_A to viewmodel_B or somehow avoid getting location twice. Any suggestion appreciated.

1 Answers

You can use a shared ViewModel across fragments If you are using fragments or use a ViewModel on the Navgraph if you are using activities you can pass geolocation between activities through bundle and pass the geolocation to ViewModel_B as a nullable parameter if you did not fetch it at ViewModel_A then the ViewModelB should fetch it otherwise it is available and use it you can also make a parent class of both view models to share the geolocation fetching code so you do not repeat the code in two classes

you can find related resources below

https://developer.android.com/codelabs/basic-android-kotlin-training-shared-viewmodel#0

https://developer.android.com/guide/navigation/navigation-programmatic#share_ui-related_data_between_destinations_with_viewmodel

Related