Android-CleanArchitecture-Kotlin
Android-CleanArchitecture-Kotlin copied to clipboard
Should we use instance variables inside a ViewModel to reuse fetched data?
What is the best approach?
// Only expose livedata
public class MyViewModel extends ViewModel {
private MutableLiveData<List<User>> users = new MutableLiveData();
public void loadUsers() {
// Do an asynchronous operation to fetch users.
users.postValue(/* ---- userList --- */);
}
}
// Expose livedata and instance variable userList
public class MyViewModel extends ViewModel {
private MutableLiveData<List<User>> users = new MutableLiveData();
private List<User> userList;
//Expose already fetched list
public List<User> getUserList() {
return userList;
}
public void loadUsers() {
// Do an asynchronous operation to fetch users.
this.userList = userList;
users.postValue(/* ---- userList --- */);
}
}
There shouldn't even be a loadUsers() method. It should be internal to the workings of the liveData, triggered in onActive by starting to observe it.
See NetworkBoundResource for a possible complex implementation, but the general idea is there.