Search code examples
android-activityandroid-livedatamutablelivedata

LiveData observe not working when activity not on screen


I am using this code

mViewModel.eventGameFinish.observe(this, { hasFinished ->
    if (hasFinished) GameFinished()
})

to observe a LiveData in my Activity. Everything is working fine but when the Activity is not on the screen, which means when onStop() is called. I would like observe to react to LiveData changes at any meaningful stage of the Activity lifecycle. Even though the user might not be using their phone and is using another app, the game should continue running in the background.

Thanks in advance.

P.S. I am new to the LiveData architecture.


Solution

  • You should use observeForever() method. Check this implementation.