使用 LiveData 从网络刷新数据

2024-03-22

我正在开发一个应用程序,该应用程序查询 github api 以获取用户列表,并且我正在遵循推荐的 android架构组件指南 https://developer.android.com/jetpack/docs/guide。从网络获取数据后,我使用 Room DB 将其存储在本地,然后使用在 LiveData 对象上观察的 ViewModel 将其显示在 UI 上(这工作正常)。但是,我希望能够有一个按钮,当且仅当存在网络连接时,单击该按钮会触发刷新操作并执行网络请求以从 API 获取新数据。 问题是,当我单击该按钮时,会触发两个网络调用,一个来自刷新用户数据(),另一个来自 onCreate()期间触发的现有 LiveData。我应该如何最好地处理这种情况,以便我的刷新按钮仅执行一个网络请求,而不是像现在这样执行两个网络请求。 这是我的存储库课程:

public class UserRepository {
private final UserDao mUserDao;
private LiveData<List<GitItem>> mAllUsers;
private LiveData<GitItem> mUser;
private final GithubUserService githubUserService;
private final AppExecutors appExecutors;
private final Application application;
private static String LOG_TAG = UserRepository.class.getSimpleName();
private RateLimiter<String> repoListRateLimit = new RateLimiter<>(1, TimeUnit.MINUTES);

   public UserRepository(Application application, GithubUserService githubUserService, AppExecutors appExecutors) {
        this.application = application;
        UserRoomDatabase db = UserRoomDatabase.getDatabase(application);
        mUserDao = db.userDao();
        this.githubUserService = githubUserService;
        this.appExecutors = appExecutors;
    }

    public LiveData<GitItem> getUser(int userId) {
        LiveData<GitItem> user = mUserDao.loadUser(userId);
        Log.d(LOG_TAG, "retrieved user from database successful");
        return user;
    }

    public LiveData<Resource<List<GitItem>>> getAllUsers() {
        //ResultType, RequestType
        /**
         * List<GitItem> is the [ResultType]
         * GithubUser is the [RequestType]
         */
        return new NetworkBoundResource<List<GitItem>, GithubUser>(appExecutors) {

            @Override
            protected void saveCallResult(@NonNull GithubUser item) {
                Log.d(LOG_TAG, "call to insert results to db");
                mUserDao.insertUsers(item.getItems());
            }

            @Override
            protected boolean shouldFetch(@Nullable List<GitItem> data) {
                Log.d(LOG_TAG, "null?" + (data == null));
                Log.d(LOG_TAG, "empty? " + (data.isEmpty()));
                Log.d(LOG_TAG, "rate? " + (repoListRateLimit.shouldFetch("owner")));
                Log.d(LOG_TAG, "should fetch? " + (data.isEmpty() || repoListRateLimit.shouldFetch("owner")));
                return data.isEmpty() || data == null;

            }

            @NonNull
            @Override
            protected LiveData<List<GitItem>> loadFromDb() {
                Log.d(LOG_TAG, " call to load from db");
                return mUserDao.getAllUsers();
            }

            @NonNull
            @Override
            protected LiveData<ApiResponse<GithubUser>> createCall() {
                Log.d(LOG_TAG, "creating a call to network");
                return githubUserService.getGithubUsers("language:java location:port-harcourt");
            }

            @Override
            protected GithubUser processResponse(ApiResponse<GithubUser> response) {
                return super.processResponse(response);
            }
        }.asLiveData();
    }


    public LiveData<Resource<List<GitItem>>> refreshUserData() {
        //ResultType, RequestType
        /**
         * List<GitItem> is the [ResultType]
         * GithubUser is the [RequestType]
         */
        return new NetworkBoundResource<List<GitItem>, GithubUser>(appExecutors) {

            @Override
            protected void saveCallResult(@NonNull GithubUser item) {
                Log.d(LOG_TAG, "call to insert results to db");
                mUserDao.insertUsers(item.getItems());
            }

            @Override
            protected boolean shouldFetch(@Nullable List<GitItem> data) {
                Log.d(LOG_TAG, "refreshUserData");
                return true;
            }

            @NonNull
            @Override
            protected LiveData<List<GitItem>> loadFromDb() {
                Log.d(LOG_TAG, "refreshUserData");
                Log.d(LOG_TAG, " call to load from db");
                return mUserDao.getAllUsers();
            }

            @NonNull
            @Override
            protected LiveData<ApiResponse<GithubUser>> createCall() {
                Log.d(LOG_TAG, "refreshUserData");
                Log.d(LOG_TAG, "creating a call to network");
                return githubUserService.getGithubUsers("language:java location:port-harcourt");
            }

            @Override
            protected GithubUser processResponse(ApiResponse<GithubUser> response) {
                return super.processResponse(response);
            }
        }.asLiveData();
    }

    public Application getApplication() {
        return application;
    }
}

我的 ViewModel 类是:

public class UserProfileViewModel extends AndroidViewModel {
    private UserRepository mRepository;


    public UserProfileViewModel(UserRepository mRepository) {
        super(mRepository.getApplication());
        this.mRepository = mRepository;
      }

    public LiveData<Resource<List<GitItem>>> getmAllUsers() {
        return mRepository.getAllUsers();
      }

    public LiveData<Resource<List<GitItem>>> refreshUserData() {
        return mRepository.refreshUserData();
      }

    public LiveData<GitItem> getUser(int userId) {
        return mRepository.getUser(userId);
      }
    }

我的 MainActivity 类:

    public class MainActivity extends AppCompatActivity implements GithubAdapter.ListItemClickListener {
    private RecyclerView mRecyclerView;
    private UserProfileViewModel mUserViewModel;
    public static final String USER_ID = "userId";
    private ConnectivityManager cm;
    private boolean isConnected;
    private UserRepository mRepository;
    private  GithubUserService mGithubUserService;

    private NetworkInfo activeNetwork;
    private Picasso mPicasso;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mGithubUserService = GithubApplication.get(MainActivity.this).getGithubUserService();
        mPicasso = GithubApplication.get(MainActivity.this).getPicasso();

        mRepository = new UserRepository(getApplication(), mGithubUserService, new AppExecutors());


        // the factory and its dependencies instead should be injected with DI framework like Dagger
        ViewModelFactory factory = new ViewModelFactory(mRepository);

        mUserViewModel = ViewModelProviders.of(this, factory).get(UserProfileViewModel.class);

        //  initViews();
        mRecyclerView = findViewById(R.id.users_recycler);
        final GithubAdapter mAdapter = new GithubAdapter(this, this, mPicasso);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);

        getUsers(mAdapter);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //check if there is a network connection
                // if there is a network connection the LoaderManager is called but
                //  displays a message if there's no network connection
                activeNetwork = cm.getActiveNetworkInfo();
                isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
                if (isConnected) {
                    mUserViewModel.refreshUserData().observe(MainActivity.this, new Observer<Resource<List<GitItem>>>() {
                        @Override
                        public void onChanged(@Nullable Resource<List<GitItem>> listResource) {
//                            Toast.makeText(MainActivity.this, "second" + listResource.status, Toast.LENGTH_LONG).show();
                            Snackbar.make(view, "refresh:" + listResource.status, Snackbar.LENGTH_LONG)
                                    .setAction("Action", null).show();
                            mAdapter.setUsers(listResource.data);
                        }
                    });

                } else {
                    Snackbar.make(view, "no connection", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();

                }

            }
        });


    }



 private void getUsers(GithubAdapter mAdapter) {
        mUserViewModel.getmAllUsers().observe(this, new Observer<Resource<List<GitItem>>>() {
            @Override
            public void onChanged(@Nullable Resource<List<GitItem>> listResource) {
                Toast.makeText(MainActivity.this, "" + listResource.status, Toast.LENGTH_LONG).show();
                mAdapter.setUsers(listResource.data);
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onListItemClick(int userId) {
        Intent detailIntent = new Intent(MainActivity.this, 
        DetailActivity.class);
        detailIntent.putExtra(USER_ID, userId);
        startActivity(detailIntent);
      }
    }

你可以找到完整的代码here https://github.com/Ikhiloya/GithubDevs/tree/constructor-DI


最好的方法是在 onCreate 方法的 MainActivity 中注册您的 LiveData 并像您一样监听数据库更改。在 FAB onClick 中,只需发出网络请求并将其保存到数据库,无需 LiveData。 onCreate方法中的LiveData会被触发。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 LiveData 从网络刷新数据 的相关文章

  • 将二进制数转换为包含每个二进制数的数组

    我试图将二进制值转换为每个 1 0 的列表 但我得到默认的二进制值而不是列表 我有一个字符串 我将每个字符转换为二进制 它给了我一个列表 其中每个字符都有一个字符串 现在我试图将每个字符串拆分为值为 0 1 的整数 但我什么也得不到 if
  • Cassandra 会话与集群 有什么可分享的?

    考虑 Cassandra 的 Session 和 Cluster 类 Java 驱动程序 我想知道有什么区别 在 Hibernate 中 每次都会创建一个会话并共享会话工厂 从许多来源我了解到 它被认为是创建一个会话并在多个线程之间共享它
  • 如何设置 Swashbuckle 与 Microsoft.AspNetCore.Mvc.Versioning

    我们有asp net core webapi 我们添加了Microsoft AspNetCore Mvc Versioning and Swashbuckle拥有招摇的用户界面 我们将控制器指定为 ApiVersion 1 0 Route
  • 如何在不同的目录中执行python脚本?

    Solved对于可能觉得这有帮助的人 请参阅下面我的答案 我有两个脚本 a py 和 b py 在我当前的目录 C Users MyName Desktop MAIN 中 我运行 gt python a py 第一个脚本 a py 在我当前
  • 如何使用 jQuery 和“this”捕获更改的表单元素值

    我有以下代码 每当我的 Web 表单中发生元素更改时 该代码都会起作用 我一直在纠结的是如何捕捉表单字段元素 id name and 改变值当更改事件被触发时 谁能帮我解决这个问题吗 Thanks JavaScript
  • Android Studio 3.0 中的 DexGuard 集成

    我已升级我的 Android 项目以使用最新的 Android Studio 3 0 功能 从那时起 我在每次 Gradle 同步时都会收到以下警告消息 警告 您正在使用的插件之一支持 Java 8 语言 特征 要尝试 Android 插件
  • 闪亮的本地部署错误:输入字符串 1 无效 UTF-8

    我很惊讶地发现一个突然的错误 我的 ShinyApp 停止工作并出现未知错误 提示 输入字符串 1 无效 UTF 8 即使在昨天 该应用程序也可以正常运行 但是突然停止了 下面是我运行时的错误描述runApp gt runApp Liste
  • 在Python中使用os.makedirs创建目录时出现权限问题

    我只是想处理上传的文件并将其写入工作目录中 该目录的名称是系统时间戳 问题是我想以完全权限创建该目录 777 但我不能 使用以下代码创建的目录755权限 def handle uploaded file upfile cTimeStamp
  • 将蒙版图像作为 PNG 文件写入磁盘

    基本上 我从网络服务器下载图像 然后将它们缓存到磁盘上 但在这样做之前 我想屏蔽它们 我正在使用每个人似乎都指出的屏蔽代码 可以在这里找到 http iosdevelopertips com cocoa how to mask an ima
  • Java编程编译jar

    我有一个文本文件中的java源代码 必须在源代码中输入一些自定义的硬编码变量 然后将其转换为 jar 这是可行的 但是当我运行 jar 时 找不到 Main 类 当我用 WinRAR 解压 jar 文件时 我似乎找不到错误 当我通过 cmd
  • Android 中用于过渡的自定义动画对象?

    我想用一些更奇特的东西来覆盖 Android 中的默认活动转换 我想做的事情不能用通常使用的 XML 集来完成 所以我不能使用overridePendingTransition因为它只接受对基于 XML 的动画资源的整数引用 我想做的是创建
  • dplyr::mutate 添加多个值

    网上有几个与此相关的问题dplyr Github 存储库 https github com hadley dplyr已经 并且至少有一个相关的问题 但没有一个问题完全涵盖了我的问题 我认为 在 dplyr mutate 调用中添加多列 ht
  • git jenkins 中未找到存储库

    我正在使用 jenkins 2 64 并安装了最新的插件 我试图在 jenkins 中设置 git 存储库并给出凭据 但给出错误无法连接存储库 状态代码为 128 Cloning repository https github com so
  • 如何使 Django 自定义管理命令参数不再需要?

    我正在尝试在 django 中编写自定义管理命令 如下所示 class Command BaseCommand def add arguments self parser parser add argument delay type int
  • 使用 ActivePerl 时为什么必须指定带有备份扩展的 -i 开关?

    除非我使用备份扩展指定它们 否则我无法就地编辑在 ActivePerl 下运行的 Perl 单行代码 C gt perl i ape splice F 2 0 q inserted text qq F n file1 txt Can t d
  • 是什么让 DVCS 中的合并变得如此简单?

    我读于乔尔谈软件 http www joelonsoftware com items 2010 03 17 html 通过分布式版本控制 分布式部分实际上不是 最有趣的部分 有趣的是 这些 系统根据变化来思考 而不是 就版本而言 and a
  • 如何获取通过网络驱动器访问的文件的 UNC 路径?

    我正在 VC 中开发一个应用程序 其中网络驱动器用于访问文件 驱动器由用户手动分配 然后在应用程序中选择驱动器 这会导致驱动器并不总是映射到相同的服务器 我该如何获取此类文件的 UNC 路径 这主要是为了识别目的 这是我用来将普通路径转换为
  • 带有包含布局的导航抽屉布局

    我认为我的问题实际上很简单 但我不知道如何解决 有一个工作导航抽屉 代码如下
  • 相当于 JavaScript 中 Ruby 的each_cons

    许多语言都曾提出过这个问题 但 javascript 却没有 Ruby 有方法Enumerable each cons https devdocs io ruby 2 5 enumerable method i each cons看起来像这
  • 通过jquery ajax()和serialize()提交html表单

    我想通过 jquery ajax 提交此表单 这是我所做的 但它不起作用 即表单正在提交并刷新页面 但我没有看到响应 即在同一页面上打印数组 HTML

随机推荐