Skip to content

Instantly share code, notes, and snippets.

@lessandro
Created October 11, 2012 19:11
Show Gist options
  • Select an option

  • Save lessandro/3874790 to your computer and use it in GitHub Desktop.

Select an option

Save lessandro/3874790 to your computer and use it in GitHub Desktop.
Promises for Android
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import android.os.AsyncTask;
import android.util.Log;
public class Promise<T> {
private List<Callback<T>> callbacks = new ArrayList<Callback<T>>();
private boolean resolved = false;
private T value;
public void resolve(T value) {
if (this.resolved) {
return;
}
this.value = value;
this.resolved = true;
for (Callback<T> callback : this.callbacks) {
this.runCallback(callback);
}
}
private static <T> T runTask(Callable<T> task) {
try {
return task.call();
} catch (Exception e) {
Log.e(Utility.TAG, "Error", e);
return null;
}
}
private void runCallback(Callback<T> callback) {
try {
callback.call(this.value);
} catch (Exception e) {
Log.e(Utility.TAG, "Error", e);
}
}
public void then(Callback<T> callback) {
if (this.resolved) {
this.runCallback(callback);
} else {
this.callbacks.add(callback);
}
}
public <U> Promise<U> filter(final Filter<T, U> filter) {
final Promise<U> promise = new Promise<U>();
this.then(new Callback<T>() {
public void call(T arg) {
promise.resolve(filter.filter(arg));
}
});
return promise;
}
public <U> Promise<U> filterAsync(final Filter<T, U> filter) {
final Promise<U> promise = new Promise<U>();
this.then(new Callback<T>() {
public void call(final T arg) {
promise.resolveAsync(new Callable<U>() {
public U call() throws Exception {
return filter.filter(arg);
}
});
}
});
return promise;
}
private void resolveAsync(final Callable<T> task) {
new AsyncTask<Void, Void, T>() {
@Override
protected T doInBackground(Void... params) {
return Promise.runTask(task);
}
@Override
protected void onPostExecute(T result) {
super.onPostExecute(result);
Promise.this.resolve(result);
}
}.execute();
}
public static <T> Promise<T> async(final Callable<T> task) {
final Promise<T> promise = new Promise<T>();
promise.resolveAsync(task);
return promise;
}
public static <T> Promise<T> sync(final Callable<T> task) {
Promise<T> promise = new Promise<T>();
promise.resolve(Promise.runTask(task));
return promise;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment