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

前端 未结 5 1335
梦毁少年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:41

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

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

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

提交回复
热议问题