Android LiveData 值未从后台发送
Android LiveData value not dispatched coming from background
阅读 LiveData
文档发现 here,我遇到了这个部分:
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.
当我创建一个空白项目来测试这个时,我发现最新的数据从后台没有被调度。
来自 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")
})
去后台再回来的时候,LiveData
持有的最新数据是否应该重新发送给观察者?
更新:
请求的 ViewModel 代码:
class MyViewModel : ViewModel() {
val textLiveData = MutableLiveData<String>()
fun buttonClicked() {
textLiveData.value = "new text value"
}
}
因此,经过大量调查,我将使用两个场景来分享我的答案,以便于理解
场景 1:
- 应用程序在前台
Observer
接收来自 LiveData
的最新数据更改
- 应用进入后台
- 从后台返回时,
LiveData
将不会 发送值,因为 Observer
已经 consumed/has 最新更改。
场景 2:
- 应用程序在前台
- Observer 从
LiveData
接收到最新的数据变化
- 应用进入后台。
- 当 App 在后台时,LiveData 收到一个新值。
- 由于应用程序仍在后台并且
Observer
未处于活动状态,因此 LiveData
将不会发送值更改。
- 当回到前台并且
Observer
再次处于活动状态时,LiveData
会发送最新的值,因为它已更改
阅读 LiveData
文档发现 here,我遇到了这个部分:
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.
当我创建一个空白项目来测试这个时,我发现最新的数据从后台没有被调度。
来自 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")
})
去后台再回来的时候,LiveData
持有的最新数据是否应该重新发送给观察者?
更新:
请求的 ViewModel 代码:
class MyViewModel : ViewModel() {
val textLiveData = MutableLiveData<String>()
fun buttonClicked() {
textLiveData.value = "new text value"
}
}
因此,经过大量调查,我将使用两个场景来分享我的答案,以便于理解
场景 1:
- 应用程序在前台
Observer
接收来自LiveData
的最新数据更改
- 应用进入后台
- 从后台返回时,
LiveData
将不会 发送值,因为Observer
已经 consumed/has 最新更改。
场景 2:
- 应用程序在前台
- Observer 从
LiveData
接收到最新的数据变化
- 应用进入后台。
- 当 App 在后台时,LiveData 收到一个新值。
- 由于应用程序仍在后台并且
Observer
未处于活动状态,因此LiveData
将不会发送值更改。 - 当回到前台并且
Observer
再次处于活动状态时,LiveData
会发送最新的值,因为它已更改