Android-CleanArchitecture-Kotlin icon indicating copy to clipboard operation
Android-CleanArchitecture-Kotlin copied to clipboard

Should we use instance variables inside a ViewModel to reuse fetched data?

Open hernandazevedozup opened this issue 6 years ago • 1 comments

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  --- */);
    }
}

hernandazevedozup avatar Sep 16 '19 14:09 hernandazevedozup

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.

Zhuinden avatar Sep 16 '19 15:09 Zhuinden