Last active
December 12, 2017 03:11
-
-
Save ncruces/312a48c86614c8bac897a37365257ddf to your computer and use it in GitHub Desktop.
AsyncTaskLoader that can be interrupted by calling cancelLoadInBackground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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