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

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

问题描述

最近,我正在探索Google最近引入的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()函数中,我异步获取数据,这里我将首先检查数据库(房间)中的数据

  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.

推荐的做法是什么?

如果我启动ServiceloadUsers()方法调用API,如何从该Service更新MutableLiveData<List<User>> 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?

推荐答案

我假设您使用的是

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)
}

由于usersLiveData,因此Room数据库负责向用户提供数据,无论其插入到何处.

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

Note:在类似MVVM的体系结构中,存储库主要负责检查和提取本地数据和远程数据.

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天全站免登陆