Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
hernandazevedozup opened this issue Sep 16, 2019 · 1 comment

Comments

@hernandazevedozup
Copy link

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
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants