Skip to content

Instantly share code, notes, and snippets.

@sergiandreplace
Created May 18, 2015 16:18
Show Gist options
  • Save sergiandreplace/db77cf3dd3bbac10aacc to your computer and use it in GitHub Desktop.
Save sergiandreplace/db77cf3dd3bbac10aacc to your computer and use it in GitHub Desktop.
Task handler
package com.tempos21.taskexecutor;
import android.os.Handler;
import java.util.Random;
/**
* Base class for executable tasks
*/
public abstract class Task<I, O> {
private boolean executing = false;
private static Random rnd = new Random(System.currentTimeMillis());
private Handler handler;
private O result;
private OnTaskResultListener<O> onTaskResultListener;
/**
* Executes the task and return the result if succesful
* @return The result of the task
* @throws Exception If the task finished with an error
*/
public O execute(final I input) throws Exception {
executing = true;
O t = perform(input);
executing = false;
return t;
}
/**
* Executes the task in another thread. Result will be delivered via listener.
* @return An id to recognize the task when listener invoked
*/
public long executeAsync(final I input) {
executing = true;
handler=new Handler();
final long id = rnd.nextInt(Integer.MAX_VALUE);
new Thread() {
@Override
public void run() {
try {
finishSuccess(id, perform(input));
}catch (Exception e) {
finishFailure(id, e);
}
executing = false;
}
}.start();
return id;
}
protected abstract O perform(I input) throws Exception;
protected void finishSuccess(final long id, final O result) {
handler.post(new Runnable() {
@Override
public void run() {
if (onTaskResultListener != null) {
onTaskResultListener.onTaskSuccess(id, result);
}
}
});
}
protected void finishFailure(final long id, final Exception error) {
handler.post(new Runnable() {
@Override
public void run() {
if (onTaskResultListener != null) {
onTaskResultListener.onTaskFailure(id, error);
}
}
});
}
public OnTaskResultListener<O> getOnTaskResultListener() {
return onTaskResultListener;
}
public void setClientResultListener(OnTaskResultListener<O> onTaskResultListener) {
this.onTaskResultListener = onTaskResultListener;
}
public interface OnTaskResultListener<T> {
public void onTaskSuccess(long id, T result);
public void onTaskFailure(long id, Exception error);
}
public boolean isExecuting() {
return executing;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment