Android LiveData value not dispatched coming from background

Viewed 1010

Reading the LiveData documentation found here, I came across this section:

If a lifecycle becomes inactive, it receives the latest data upon becoming active again. For example, an activity that was in the background receives the latest data right after it returns to the foreground.

When I create a blank project to test this, I discover that latest data is not dispatched when coming from background.

Sample code from onCreate():

viewModel = ViewModelProvider(this).get(MyViewModel::class.java)

button.setOnClickListener {
    viewModel.buttonClicked()
}

viewModel.textLiveData.observe(this, Observer {
    textview.text = it
    Log.d("TEST", "new data = $it")
})

When going to background and coming back, should the latest data that the LiveData is holding be dispatched again to the observer?

UPDATE:

ViewModel code as requested:

class MyViewModel : ViewModel() {

    val textLiveData = MutableLiveData<String>()

    fun buttonClicked() {
        textLiveData.value = "new text value"
    }
}
1 Answers

So, after a lot of investigation, I will share my answer using two scenarios to make it easier to grasp

Scenario 1:

  • App is in foreground
  • Observer receives latest data change from LiveData
  • App goes to background
  • When coming back from background, LiveData will NOT dispatch the value since the Observer already consumed/has the latest change.

Scenario 2:

  • App is in foreground
  • Observer receives latest data change from LiveData
  • App goes to background.
  • While App is in background, LiveData receives a new value.
  • Since App is still in background and Observer is not in an active state, LiveData will not dispatch the value change yet.
  • When coming back to foreground and Observer is in an active state again, LiveData does dispatch the latest value since it has changed
Related