Skip to content

Instantly share code, notes, and snippets.

@yyunikov
Created October 26, 2014 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yyunikov/2dc5390bb1edefa8e84e to your computer and use it in GitHub Desktop.
Save yyunikov/2dc5390bb1edefa8e84e to your computer and use it in GitHub Desktop.
Android: example implementation of Loader for generics
/**
* An {@link AsyncTaskLoader} implementation for loading objects like entities, cursors, etc.
* which takes care of delivering and reseting results. For Cursors you need to override
* onReleaseResources and perform all kind there, e.g. call close() method.
*/
public abstract class AsyncGenericLoader<T> extends AsyncTaskLoader<T> {
protected T mItems;
public AsyncGenericLoader(final Context context) {
super(context);
}
/**
* Called when there is new data to deliver to the client. The
* super class will take care of delivering it.
*/
@Override
public void deliverResult(final T items) {
if (isReset()) {
// An async query came in while the loader is stopped. We
// don't need the result.
if (items != null) {
onReleaseResources(items);
}
}
mItems = items;
if (isStarted()) {
// If the Loader is currently started, we can immediately
// deliver its results.
super.deliverResult(items);
}
// At this point we can release the resources associated with
// 'items'; now that the new result is delivered we
// know that it is no longer in use.
if (items != null) {
onReleaseResources(items);
}
}
/**
* Handles a request to start the Loader.
*/
@Override
protected void onStartLoading() {
if (mItems != null) {
// If we currently have a result available, deliver it
// immediately.
deliverResult(mItems);
} else {
forceLoad();
}
}
/**
* Handles a request to stop the Loader.
*/
@Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
@Override
public void onCanceled(final T items) {
super.onCanceled(items);
// At this point we can release the resources associated with 'apps'
// if needed.
onReleaseResources(items);
}
/**
* Handles a request to completely reset the Loader.
*/
@Override
protected void onReset() {
super.onReset();
onStopLoading();
if (mItems != null) {
onReleaseResources(mItems);
mItems = null;
}
}
/**
* Helper function to take care of releasing resources associated
* with an actively loaded data set.
*/
protected void onReleaseResources(final T items) {
// For a simple List<> there is nothing to do. For something
// like a Cursor, we would close it here.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment