Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing network operations from ViewModel

Tags:

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?
like image 259
Harshawardhan Upasani Avatar asked Oct 05 '17 10:10

Harshawardhan Upasani


2 Answers

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

https://youtu.be/5qlIPTDE274

like image 64
Alfredo Bejarano Avatar answered Oct 04 '22 04:10

Alfredo Bejarano


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

like image 30
Róbert Nagy Avatar answered Oct 04 '22 06:10

Róbert Nagy