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:
in the loadUsers()
function I am fetching the data asynchronously where I will first check the database(Room) for that data
If I do not get the data there I will make an API call to fetch the data from the web server.
I will insert the fetched data into the database(Room) and update the UI according the data.
What is the recommended approach to do this?
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
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…