Search code examples
android-livedataandroid-viewmodel

ViewModel Live Data observers calling on rotation


In my view model, I have two properties:

private val databaseDao = QuestionDatabase.getDatabase(context).questionDao()
val allQuestions: LiveData<List<Question>> = databaseDao.getAllQuestions()

I have observers set on "allQuestions" in my fragment and I'm noticing the observer is being called when I rotate the device. Even though the View Model is only being created once (can tell via a log statement in init()), the observer methods are still being called.

Why is this? I would think the point is to have persistency in the View Model. Ideally, I want the database questions to be only loaded once, regardless of rotation.


Solution

  • This happens because LiveData is lifecycle aware.
    And When you rotate the screen you UI Controller [Activity/Fragment] goes through various lifecycle states and lifecycle callbacks.
    And since LiveData is lifecycle aware, it updates the detail accordingly.

    I have tried to explain this with following points:

    1. When the UI Controller is offscreen, Live Data performs no updates.
    2. When the UI Controller is back on screen, it gets current data.
      (Because of this property you are getting above behavior)
    3. When UI controller is destroyed, it performs cleanup on its own.
    4. When new UI Controller starts observing live data, it gets current data.