How to update LiveData of a ViewModel from background service and Update UI

前端 未结 5 1333
梦毁少年i
梦毁少年i 2020-12-07 12:56

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

public class MyViewModel         


        
5条回答
  •  暖寄归人
    2020-12-07 13:28

    ... in the loadUsers() function I am fetching the data asynchronously ... If I start a Service to call the API from the loadUsers() method, how can I update the MutableLiveData> users variable from that Service?

    If the app is fetching user data on a background thread, postValue (rather than setValue) will be useful.

    In the loadData method there is a reference to the MutableLiveData "users" object. The loadData method also fetches some fresh user data from somewhere (for example, a repository).

    Now, if execution is on a background thread, MutableLiveData.postValue() updates outside observers of the MutableLiveData object.

    Maybe something like this:

    private MutableLiveData> users;
    
    .
    .
    .
    
    private void loadUsers() {
        // do async operation to fetch users
        ExecutorService service =  Executors.newSingleThreadExecutor();
        service.submit(new Runnable() {
            @Override
            public void run() {
                // on background thread, obtain a fresh list of users
                List freshUserList = aRepositorySomewhere.getUsers();
    
                // now that you have the fresh user data in freshUserList, 
                // make it available to outside observers of the "users" 
                // MutableLiveData object
                users.postValue(freshUserList);        
            }
        });
    
    }
    

提交回复
热议问题