Skip to content

Instantly share code, notes, and snippets.

@ericwoodruff
Last active December 21, 2015 16:48
Show Gist options
  • Save ericwoodruff/6335659 to your computer and use it in GitHub Desktop.
Save ericwoodruff/6335659 to your computer and use it in GitHub Desktop.
Android Async Task Loader with Exceptions
public interface Catchable<V, T extends Throwable> {
V getValue () throws T;
}
public class CatchableException<V, T extends Throwable> implements Catchable<V, T> {
public CatchableException (T throwable) {
this.throwable = throwable;
}
@Override
public V getValue () throws T {
throw this.throwable;
}
private T throwable;
}
public class CatchableValue<V, T extends Throwable> implements Catchable<V, T> {
public CatchableValue (V value) {
this.value = value;
}
@Override
public V getValue () {
return value;
}
private V value;
}
public abstract class CatchableAsyncTaskLoader<D, T extends Throwable> extends AsyncTaskLoader<Catchable<D, T>> {
public CatchableAsyncTaskLoader (Context context) {
super (context);
}
@SuppressWarnings("unchecked")
@Override
public Catchable<D, T> loadInBackground () {
try {
return new CatchableValue<D, T> (this.load ());
} catch (Throwable t) {
return new CatchableException<D, T> ((T) t);
}
}
@Override
protected void onStartLoading () {
forceLoad ();
}
@Override
protected void onStopLoading () {
cancelLoad ();
}
protected abstract D load () throws T;
}
public abstract class ExceptionLoaderCallbacks<D, T extends Throwable> implements LoaderCallbacks<Catchable<D, T>> {
@SuppressWarnings("unchecked")
@Override
public void onLoadFinished (Loader<Catchable<D, T>> loader, Catchable<D, T> data) {
try {
this.onSuccess (data.getValue ());
} catch (Throwable t) {
this.onException ((T) t);
}
}
protected void onException (T t) {
}
protected void onSuccess (D value) {
}
}
...
@Override
public Loader<Catchable<String, Exception>> onCreateLoader (int id, Bundle args) {
return new CatchableAsyncTaskLoader<String, Exception> (this) {
@Override
protected String load () throws Exception {
return "background loaded token"
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment