I want to use AsyncTaskLoader but it was deprecated so came to know that in place of AsyncTaskLoader I can use ViewModel and live data or mutable data but I don't know how to use them with the async task.
3 Answers
First off, I would recommend using JobScheduler/WorkManager as Google states here.
However, if you are still interested in using AsyncTask/AsyncTaskLoader
, something like this might help. Since ViewModel
holds a reference to a LiveData
and the ViewModel
updates the View (Activity or Fragment)
, you can make a background network call(using AsyncTaskLoader) and update the liveData when onLoadFinished
is called. This update of LiveData should trigger the observable and eventually the View (Activity/Fragment
)
Note: Make sure that the data you get back from the API call (For eg: <POJO.class>
) is of type MutableLiveData
/LiveData
.

- 51
- 3
Using AsyncTask with ViewModel defeats the purpose of using ViewModel.
ViewModel basic use case is:
public class MyViewModel extends ViewModel {
private MutableLiveData<List<User>> users;
public LiveData<List<User>> getUsers() {
if (users == null) {
users = new MutableLiveData<List<User>>();
loadUsers();
}
return users;
}
private void loadUsers() {
// Do an asynchronous operation to fetch users.
}
}
In the loadUsers
you are suppose to do the job - in background thread. You could use AsyncTask here but it makes no sense as you would not benefit from its doInBackground()
and onPostExecute()
methods.

- 31
- 1
LiveData with ViewModel is still latest, and you can use simple AsyncTask with Android Architecture Components (LiveData and ViewModel) in order to make AsyncTask lifecycle aware. Loader is not as efficient as this method of doing background task. Since you already know how to write AsyncTask, you only need it wrapped with LiveData and ViewModel: it works like a magic. For information on using AsyncTask with LiveData and ViewModel, you can look it up at https://medium.com/androiddevelopers/lifecycle-aware-data-loading-with-android-architecture-components-f95484159de4

- 544
- 3
- 14