Reputation: 233
Code for question on Github
I have a app which is using fragments + viewmodels. In one fragment I need to present a list of options to the user when they hit a button. I'm doing this using an AlertDialog builder and it works to solve that problem. But if I open the application, hit the button to show the alertdialog, dismiss the dialog, and then rotate the phone to trigger a teardown/buildup the alertdialog get's reshown.
I'm using Android's databinding to bind ui stuff to the ViewModel(not sure if it matters). So the basic flow is:
I have created a simple demo on github.
If you clone that repo then start the app but DONT hit the button, orientation changes go as expected. If you click the button and dismiss the dialog then rotate the phone, you'll see that the AlertDialog get's reshown.
Upvotes: 1
Views: 857
Reputation: 2699
If you are working with LiveData and events, this can help you to tackle some scenarios. In summary, you should work with SingleLiveEvents
Upvotes: 1
Reputation: 336
ViewModel's lifecycle is different than of the fragment. When the orientation changes the Fragment gets recreated but the ViewModel stays.
Now what's happening is, when you update the value of the MutableLiveData it broadcasts an update to the Observer; when the Fragment is recreated on rotation change, it subscribes to the LiveData all over again and since there is an update on the value, the MutableLiveData broadcasts the update to the newly subscribed observer.
So you should, for example, save your fragment state in onSaveInstanceState
, use the savedInstanceState to get the last update to the MutableLiveData value and check if a change had happened in the observer before showing the dialog.
Or you can move the dialog logic to the on click handler. Showing a dialog in an Observer is not a good approach in my opinion.
Upvotes: 1