Skip to content

Instantly share code, notes, and snippets.

@ncruces
Last active December 12, 2017 03:11
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 ncruces/312a48c86614c8bac897a37365257ddf to your computer and use it in GitHub Desktop.
Save ncruces/312a48c86614c8bac897a37365257ddf to your computer and use it in GitHub Desktop.
AsyncTaskLoader that can be interrupted by calling cancelLoadInBackground
package io.github.ncruces.utils;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.os.OperationCanceledException;
import static java.lang.Thread.currentThread;
import static java.lang.Thread.interrupted;
public abstract class InterruptibleAsyncTaskLoader<D> extends AsyncTaskLoader<D> {
private volatile Thread thread;
public InterruptibleAsyncTaskLoader(Context context) {
super(context);
}
public boolean isLoadInBackgroundRunning() {
return thread != null;
}
@Override
public void cancelLoadInBackground() {
Thread t = thread;
if (t != null) t.interrupt();
}
@Override
public final D loadInBackground() {
try {
thread = currentThread();
return doLoadInBackground();
} catch (InterruptedException e) {
OperationCanceledException oce = new OperationCanceledException(e.toString());
oce.initCause(e);
throw oce;
} finally {
thread = null;
interrupted();
}
}
public abstract D doLoadInBackground() throws InterruptedException;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment