How to turn this code of AsyncTask to AsyncTaskLoader since movieListFetcher.listType is an enum?
class LoadMovieList extends AsyncTask<movieListFetcher.listType, Void, Void> {
@Override
protected Void doInBackground(movieListFetcher.listType... params) {
movies = null;
switch (params[0]) {
case TOP_RATED:
movies = new movieListFetcher().getTopRatedList();
break;
case MOST_POPULAR:
movies = new movieListFetcher().getMostPopularList();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
if (movies != null) {
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
}
}
General Steps for Using AsyncTaskLoader:
o Step 1: Create a custom Loader class which extends
AsyncTaskLoader<D>; D: is the list of objects that are returned back from the background task which is implemented usingloadInBackground()method; and then override below methods:loadInBackground()>> runs in background to load the heavy work .. similar todoInBackground()ofAsyncTaskonStartLoading()>> runs once the loader is created and just beforeloadInBackground(); can be used to return previous loaded results usingdeliverResult()or to load new results by running the background task again usingforceLoad()o Step 2: Implement
LoaderCallbacks<D>in your Activity that requires the background process. This requires to implement 3 methods:onCreateLoader()>> runs in main thread to create a loader instanceonLoadFinished()>> runs in main thread to submit background results & update UI .. similar toonPostExecute()ofAsyncTaskonLoaderReset()>> reset loader datao Step 3: use the LoaderManager to start your loader whenever you need that in your activity:
To apply this in your example:
Step 1:
Step 2 & 3:
Please note that Loaders are now deprecated and replaced by LiveData & ViewModels
Hope this satisfies your need, and you can check this tutorial for more info