5

I am using ViewModel, introduced in IO/17.

I am using following guidelines provided on android developers page. https://developer.android.com/topic/libraries/architecture/viewmodel.html

Following is their sample code.

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
 }
}

I wish to perform Volley request in the 'loadUsers()' method. But I cannot do it as it needs a 'context' as follows

Volley.newRequestQueue(context).add(jsonObjectRequest);

So my question is,

  1. Is it recommended(or possible) to perform network operations inside a ViewModel??
  2. If yes(if possible), how to do it?
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • 2
    i hv got my answer...posting late... api calls can be made from VM. But since i was using volley, my only concern was passing context outside view class(activity/fragment) which causes problems. I solved this by using retrofit. – Harshawardhan Upasani Jan 05 '18 at 06:53

3 Answers3

3

You could use the AndroidViewModel class instead of ViewModel. AndroidViewModel holds a reference to the application context.

https://youtu.be/5qlIPTDE274

Alfredo Bejarano
  • 548
  • 1
  • 8
  • 22
1

Consider Dagger, that way you don't have to worry, about providing context for Volley from your ViewModel.

Róbert Nagy
  • 6,720
  • 26
  • 45
1

AndroidViewModel is subclass of ViewModel. The Difference between them is we can pass Application Context which can be used whenever Application Context is required for example to instantiate Database in Repository.

AndroidViewModel is a Application context aware ViewModel.You must use AndroidViewModel for Application Context.

public class MyViewModel extends AndroidViewModel {
private MutableLiveData<List<User>> users;
private Application application;
public MyViewModel(@NonNull Application application) {
    this.application=application;
    super(application);
}
public LiveData<List<User>> getUsers() {
    if (users == null) {
        users = new MutableLiveData<List<Users>>();
        loadUsers();
    }
    return users;
}

private void loadUsers() {
    // Pass Context to Repository
}}

You should never store a reference of activity or a view that references a activity in the ViewModel.Because ViewModel is designed to outlive a activity and it will cause Memory Leak.

Is it recommended(or possible) to perform network operations inside a ViewModel??

No, you should not perform Networking Operations inside a ViewModel.

If yes(if possible), how to do it?

Get Application Context by using AndroidModelView and pass it to Repository, as recommended by Android Team.

enter image description here

Junaid
  • 1,301
  • 1
  • 15
  • 21