Skip to content

Instantly share code, notes, and snippets.

@melix
Created June 6, 2014 09:55
Show Gist options
  • Save melix/355185ffbc1332952cc8 to your computer and use it in GitHub Desktop.
Save melix/355185ffbc1332952cc8 to your computer and use it in GitHub Desktop.
Fluent class for AsyncTask
package me.champeau.gr8confagenda.app;
import android.os.AsyncTask;
import groovy.lang.Closure;
/**
* An implementation of {@link android.os.AsyncTask} which makes it easy to deal with
* requests/callbacks using Groovy closures
*/
public class Fluent<Result, Progress> extends AsyncTask<Void, Progress, Result> {
private final Closure<Result> request;
private final ResultConsumer<Result> then;
private final Closure progress;
private Fluent(Closure<Result> request, ResultConsumer<Result> then, Closure progress) {
this.request = request;
this.then = then;
this.progress = progress;
}
@Override
protected Result doInBackground(Void... params) {
return request.call();
}
@Override
protected void onPostExecute(Result result) {
then.consume(result);
}
@Override
protected void onProgressUpdate(Progress... values) {
if (progress!=null) {
progress.call(values);
}
}
public static interface ResultConsumer<T> {
void consume(T result);
}
public static class FluentAsyncTaskBuilder<Result,Progress> {
Closure<Result> request;
Closure progress;
private FluentAsyncTaskBuilder<Result,Progress> from(Closure<Result> request) {
this.request = request;
return this;
}
FluentAsyncTaskBuilder<Result,?> onProgress(Closure progress) {
this.progress = progress;
return this;
}
void then(ResultConsumer<Result> then) {
Fluent<Result,Progress> resultFluent = new Fluent<Result,Progress>(request, then, progress);
resultFluent.execute();
}
}
public static <Result,Progress> FluentAsyncTaskBuilder<Result,Progress> async(Closure<Result> request) {
return new FluentAsyncTaskBuilder<Result,Progress>().from(request);
}
}
@leonard84
Copy link

Why is ResultConsumer the only functional interface?

Shouldn't the Fluent class set itself as delegate to the closures? How else can you check isCancelled and invoke progressUpdate? https://developer.android.com/reference/android/os/AsyncTask.html

@karfunkel
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment