T
T
Tsuzukeru2020-09-19 18:11:00
Java
Tsuzukeru, 2020-09-19 18:11:00

Why do LiveData listeners in the ViewModel fire when the screen configuration changes?

There is a fragment that holds a reference to the ViewModel. Inside the ViewModel there are several fields of type LiveData, with data.
The fragment's OnCreateView() has listeners on the LiveData of our ViewModel.
For example this one:

viewModel.networkState.observe(viewLifecycleOwner, Observer {
            when(it){
                NetworkState.LOADING -> activityContract.showProgressBar()
                NetworkState.LOADED -> activityContract.hideProgressBar()
                NetworkState.NO_INTERNET ->activityContract.showErrorDialog(NetworkState.NO_INTERNET.msg)
                NetworkState.ERROR -> activityContract.showErrorDialog(NetworkState.ERROR.msg)
                NetworkState.API_LIMIT_EXCEEDED -> activityContract.showErrorDialog(NetworkState.API_LIMIT_EXCEEDED.msg)
            }
        })

When the screen is flipped, these listeners fire even though no LiveData updates have occurred.
I covered with logs all the methods that are responsible for changing the data and did not find a single one that would work when flipped. The same data that was in LiveData before the flip gets into the listeners.
Is this a feature of the ViewModel + LiveData, or am I wrong somewhere?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
illuzor, 2020-09-19
@Tsuzukeru

The fragment is recreated and the data arrives again.
Read about activity and fragment life cycles.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question