[英]Android Architecture Components how to combine LiveData from both database and network?
There's an example provided in NetworkBoundResource, but when I tried it out, if database returns a result, it does not fetch from network anymore. NetworkBoundResource中提供了一个示例,但是当我尝试了该示例时,如果数据库返回结果,它将不再从网络获取。 What I want is display data from database and trigger network at the same time and eventually replace data in database after network completes.
我想要的是同时显示数据库中的数据并触发网络,并在网络完成后最终替换数据库中的数据。 Example codes will be much appreciated.
示例代码将不胜感激。
I would use room database to save your items in a table. 我将使用会议室数据库将您的项目保存在表中。 Then you use Paging list to observe to that table.
然后使用分页列表观察该表。 The first time you observe to that table, also do a request to network.
您第一次观察该表时,也要进行网络请求。 When you receive the response delete all items from the table and insert the new ones (all this in a repository class, and in a background thread).
当您收到响应时,请删除表中的所有项目,然后插入新项目(所有这些都在存储库类和后台线程中)。 This last step will update your paging list automatically as your paging list is observing to that room table.
最后一步将自动更新您的分页列表,因为您的分页列表正在观察该会议室表。
Guess this article could be helpful: https://proandroiddev.com/the-missing-google-sample-of-android-architecture-components-guide-c7d6e7306b8f 猜猜这篇文章可能会有所帮助: https : //proandroiddev.com/the-missing-google-sample-of-android-architecture-components-guide-c7d6e7306b8f
and the GitHub repo for this article: https://github.com/PhilippeBoisney/GithubArchitectureComponents 以及本文的GitHub存储库: https : //github.com/PhilippeBoisney/GithubArchitectureComponents
The heart of this solution is UserRepository: 此解决方案的核心是UserRepository:
public LiveData<User> getUser(String userLogin) {
refreshUser(userLogin); // try to refresh data if possible from Github Api
return userDao.load(userLogin); // return a LiveData directly from the database.
}
// ---
private void refreshUser(final String userLogin) {
executor.execute(() -> {
// Check if user was fetched recently
boolean userExists = (userDao.hasUser(userLogin, getMaxRefreshTime(new Date())) != null);
// If user have to be updated
if (!userExists) {
webservice.getUser(userLogin).enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
Toast.makeText(App.context, "Data refreshed from network !", Toast.LENGTH_LONG).show();
executor.execute(() -> {
User user = response.body();
user.setLastRefresh(new Date());
userDao.save(user);
});
}
@Override
public void onFailure(Call<User> call, Throwable t) { }
});
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.