android10 / Android-CleanArchitecture-Kotlin

This is a movies sample app in Kotlin, which is part of a serie of blog posts I have written about architecting android application using different approaches.
https://fernandocejas.com/2018/05/07/architecting-android-reloaded/
4.64k stars 921 forks source link

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

Open hernandazevedozup opened 4 years ago

hernandazevedozup commented 4 years ago

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  --- */);
    }
}
Zhuinden commented 4 years ago

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.