当 Room 数据库发生变化时,LiveData 会更新我的可观察对象
LiveData updates my observable when changes occur in Room database
我使用 LiveData 显示 Room 中 table 中的记录数。我调用一个函数来检索这个计数,并在接收到它时调用观察者来显示计数。这按预期工作。但我还有一项服务 运行ning,它从后端检索数据并将其存储在我从中读取计数的同一 table 中。但是每当数据被存储时,每次都会调用 observable 并更新显示的计数。我不确定为什么会这样。事实上,我确实希望这发生。我只是不明白为什么会这样。当我 运行 我的代码检索计数时,它是使用 RxJava 完成的。因此,当调用完成时,我看不出有任何理由可以使用每个数据存储来更新计数的可观察值。唯一可能的原因是 Room 会跟踪我的计数查询并在存储数据时执行它。那可能吗?这是我获取计数的代码:
在我的片段中观察到:
viewModel.onConnectionsCountRetrieved.observe(this, Observer { count ->
var title = getString(R.string.connections)
if (count > 0)
title += " (" + "%,d".format(count) + ")"
(activity as MainActivity).getSupportActionBar()?.title = title
})
在我的视图模型中:
val onConnectionsCountRetrieved: MutableLiveData<Int> = MutableLiveData()
@SuppressLint("CheckResult")
fun getConnectionsCount() {
val disposable = connectionsBO.getConnectionsCount()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ count -> onConnectionsCountRetrieved.postValue(count) },
{ ex -> App.context.displayErrorMessage(R.string.problem_retrieving_total_connection_count) }
)
disposables.add(disposable)
}
来自房间documentations:
Observable queries
When performing queries, you'll often want your
app's UI to update automatically when the data changes. To achieve
this, use a return value of type LiveData in your query method
description. Room generates all necessary code to update the LiveData
when the database is updated.
Room 也为 RxJava 提供了相同的功能。您可以在生成的 class YourDao_Impl.java
.
中看到查询的实现
我使用 LiveData 显示 Room 中 table 中的记录数。我调用一个函数来检索这个计数,并在接收到它时调用观察者来显示计数。这按预期工作。但我还有一项服务 运行ning,它从后端检索数据并将其存储在我从中读取计数的同一 table 中。但是每当数据被存储时,每次都会调用 observable 并更新显示的计数。我不确定为什么会这样。事实上,我确实希望这发生。我只是不明白为什么会这样。当我 运行 我的代码检索计数时,它是使用 RxJava 完成的。因此,当调用完成时,我看不出有任何理由可以使用每个数据存储来更新计数的可观察值。唯一可能的原因是 Room 会跟踪我的计数查询并在存储数据时执行它。那可能吗?这是我获取计数的代码:
在我的片段中观察到:
viewModel.onConnectionsCountRetrieved.observe(this, Observer { count ->
var title = getString(R.string.connections)
if (count > 0)
title += " (" + "%,d".format(count) + ")"
(activity as MainActivity).getSupportActionBar()?.title = title
})
在我的视图模型中:
val onConnectionsCountRetrieved: MutableLiveData<Int> = MutableLiveData()
@SuppressLint("CheckResult")
fun getConnectionsCount() {
val disposable = connectionsBO.getConnectionsCount()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ count -> onConnectionsCountRetrieved.postValue(count) },
{ ex -> App.context.displayErrorMessage(R.string.problem_retrieving_total_connection_count) }
)
disposables.add(disposable)
}
来自房间documentations:
Observable queries
When performing queries, you'll often want your app's UI to update automatically when the data changes. To achieve this, use a return value of type LiveData in your query method description. Room generates all necessary code to update the LiveData when the database is updated.
Room 也为 RxJava 提供了相同的功能。您可以在生成的 class YourDao_Impl.java
.