如何从后台服务和更新 UI 更新 ViewModel 的 LiveData [英] How to update LiveData of a ViewModel from background service and Update UI

查看:65
本文介绍了如何从后台服务和更新 UI 更新 ViewModel 的 LiveData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我正在探索谷歌最近推出的 Android 架构.从 文档 我发现了这个:

Recently I am exploring Android Architecture, that has been introduced recently by google. From the Documentation I have found this:

public class MyViewModel extends ViewModel {
    private MutableLiveData<List<User>> users;
    public LiveData<List<User>> getUsers() {
        if (users == null) {
            users = new MutableLiveData<List<Users>>();
            loadUsers();
        }
        return users;
    }

    private void loadUsers() {
        // do async operation to fetch users
    }
}

活动可以按如下方式访问此列表:

the activity can access this list as follows:

public class MyActivity extends AppCompatActivity {
    public void onCreate(Bundle savedInstanceState) {
        MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
        model.getUsers().observe(this, users -> {
            // update UI
        });
    }
}

我的问题是,我要这样做:

My Question is, I am going to do this:

  1. loadUsers() 函数中,我将异步获取数据,我将首先检查数据库(Room)中的数据

  1. in the loadUsers() function I am fetching the data asynchronously where I will first check the database(Room) for that data

如果我没有在那里获取数据,我将进行 API 调用以从 Web 服务器获取数据.

If I do not get the data there I will make an API call to fetch the data from the web server.

我会将获取的数据插入数据库(Room)并根据数据更新UI.

I will insert the fetched data into the database(Room) and update the UI according the data.

推荐的方法是什么?

如果我启动一个 Service 以从 loadUsers() 方法调用 API,我该如何更新 MutableLiveData>来自那个 Service 的 users 变量?

If I start a Service to call the API from the loadUsers() method, how can I update the MutableLiveData<List<User>> users variable from that Service?

推荐答案

我假设您正在使用 android 架构组件.实际上,无论您在何处调用 service、asynctask 或 handler 来更新数据都无关紧要.您可以使用 postValue(..) 方法插入来自服务或异步任务的数据.你的类看起来像这样:

I am assuming that you are using android architecture components. Actually it doesn't matter wherever you are calling service, asynctask or handler to update the data. You can insert the data from the service or from the asynctask using postValue(..) method. Your class would look like this:

private void loadUsers() {
    // do async operation to fetch users and use postValue() method
    users.postValue(listOfData)
}

由于usersLiveDataRoom 数据库负责在任何插入的地方提供用户数据.

As the users is LiveData, Room database is responsible for providing users data wherever it is inserted.

注意: 在类似 MVVM 的架构中,repository 主要负责检查和拉取本地数据和远程数据.

Note: In MVVM like architecture, the repository is mostly responsible for checking and pulling local data and remote data.

这篇关于如何从后台服务和更新 UI 更新 ViewModel 的 LiveData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆