简体   繁体   English

Android Architecture Components如何结合数据库和网络中的LiveData?

[英]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.

相关问题 Android体系结构组件:如何通过ViewModel观察存储库中的LiveData - Android Architecture Components: How is LiveData in the repository observed by a ViewModel 如何在Android体系结构组件中使用RxJava代替LiveData? - How to use RxJava instead of LiveData with android architecture components? Android架构组件,Android绑定和LiveData - Android Architecture Components, android binding and LiveData 如何将架构组件与Android上的数据绑定相结合? - how to combine Architecture Components with data binding on android? 架构组件刷新LiveData - Architecture Components refresh LiveData Android架构组件网络线程 - Android Architecture Components network threads Android:在 DAO 中使用 Room 数据库和 LiveData 的干净架构 - Android: clean architecture with Room database and LiveData in DAO Android架构组件室库 - 如何处理来自DAO的livingata - Android architecture component room library - How to handle livedata from DAO 如何阻止 LiveData 观察者在 Android MVVM 架构中自动触发? - How to stop LiveData observer from firing automatically in Android MVVM architecture? Android架构组件ViewModel可以从多个LiveData返回模型组成一个对象吗? - Can an Android Architecture Components ViewModel compose an object from multiple LiveData returning models?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM