简体   繁体   English

为什么 LiveData 观察者在设置观察者之前值改变时执行?

[英]Why LiveData observer execute when value changed before set observer?

I test LiveData like this.我像这样测试LiveData

// 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.我认为.... (livedata).observe意思是开始观察 liveData 值的变化。
I don't think the value changed before the observer is set is not observable.我不认为在设置观察者之前更改的值是不可观察的。
But, it print hello ....但是,它打印hello ....
Am I misunderstood about live data observers?我是否误解了实时数据观察者?

When you start observing a LiveData, if the LiveData has a value already, it will replay that value to the observer immediately.当您开始观察 LiveData 时,如果 LiveData 已经有一个值,它会立即将该值重播给观察者。 This is by design, because LiveData is typically in a ViewModel that outlives the views.这是设计使然,因为 LiveData 通常位于比视图寿命更长的 ViewModel 中。 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.所有视图都将使用 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.如果它不这样做,那么当屏幕旋转并重新创建活动/片段时,它们将只是坐在那里而没有任何可观察的东西,从而违背了使用 ViewModel 来保留比视图更持久的状态的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM