Home > Mobile >  Why LiveData observer execute when value changed before set observer?
Why LiveData observer execute when value changed before set observer?

Time:10-21

I test LiveData like this.

// MainActivity.kt
class MainActivity : AppCompatActivity() {
    
    val testViewModel: TestViewModel by viewModels()
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        testViewModel.testLiveData.value = true
        testViewModel.testLiveData.observe(this) {
            println("Hello")
        }
    }
}
// TestViewModel.kt
class TestViewModel : ViewModel(){
    val testLiveData = MutableLiveData<Boolean>()
    
}

I think.... (livedata).observe mean start observe about liveData value change.
I don't think the value changed before the observer is set is not observable.
But, it print hello....
Am I misunderstood about live data observers?

CodePudding user response:

When you start observing a LiveData, if the LiveData has a value already, it will replay that value to the observer immediately. This is by design, because LiveData is typically in a ViewModel that outlives the views. For example, when the screen rotates, all the views are recreated and observations begin again. All the views will be updated with the latest values of the LiveData. If it didn't behave this way, then when the screen rotates and Activities/Fragments are recreated, they would just sit there and have nothing to observe, defeating the purpose of using a ViewModel to retain state that outlives views.

  • Related