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,
You could use the AndroidViewModel class instead of ViewModel. AndroidViewModel holds a reference to the application context.
https://youtu.be/5qlIPTDE274
Consider Dagger, that way you don't have to worry, about providing context
for Volley
from your ViewModel
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With