Skip to content

Instantly share code, notes, and snippets.

@karfunkel
Created May 15, 2015 08:57
Show Gist options
  • Save karfunkel/6eba3c237890f90c2779 to your computer and use it in GitHub Desktop.
Save karfunkel/6eba3c237890f90c2779 to your computer and use it in GitHub Desktop.
Extended Fluent class for AsyncTask - based on https://gist.github.com/melix/355185ffbc1332952cc8
package org.aklein.android.ext;
import android.os.AsyncTask
import java.util.concurrent.TimeUnit;
/**
* 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<Object, Progress, Result> {
private Closure<Result> request
private Closure<Void> first
private Closure<Void> then
private Closure<Void> cancelled
private Closure progress
@Override
protected Result doInBackground(Object... params) {
return request()
}
@Override
protected void onPreExecute() {
if(first)
first()
}
@Override
protected void onPostExecute(Result result) {
if(then)
then(result)
}
@Override
protected void onProgressUpdate(Progress... values) {
if (progress)
progress.call(values.asType(progress.getParameterTypes().first()))
}
@Override
protected void onCancelled(Result result) {
if(cancelled)
cancelled(result)
}
@Override
protected void onCancelled() {
if(cancelled)
cancelled()
}
protected final void progress(Progress... values) {
publishProgress(values)
}
static class FluentAsyncTaskBuilder<Result, Progress> {
Fluent<Result, Progress> task
private FluentAsyncTaskBuilder(Fluent<Result, Progress> task) {
this.task = task
}
private FluentAsyncTaskBuilder<Result, Progress> from(@DelegatesTo(value = Fluent, strategy = Closure.OWNER_FIRST) Closure<Result> request) {
request.delegate = task
task.request = request
return this
}
FluentAsyncTaskBuilder<Result, ?> onProgress(@DelegatesTo(value = Fluent, strategy = Closure.OWNER_FIRST) Closure progress) {
progress.delegate = task
task.progress = progress
return this
}
FluentAsyncTaskBuilder<Result, ?> first(@DelegatesTo(value = Fluent, strategy = Closure.OWNER_FIRST) Closure first) {
first.delegate = task
task.first = first
return this
}
FluentAsyncTaskBuilder<Result, ?> then(Closure then) {
then.delegate = task
task.then = then
return this
}
FluentAsyncTaskBuilder<Result, ?> onCancelled(Closure cancelled) {
cancelled.delegate = task
task.cancelled = cancelled
return this
}
AsyncTask<Object, Progress, Result> call() {
task.execute()
}
Result get() {
task.get()
}
Result get(long timeout, TimeUnit unit) {
task.get(timeout, unit)
}
}
static <Result, Progress> FluentAsyncTaskBuilder<Result, Progress> async(@DelegatesTo(value = Fluent, strategy = Closure.OWNER_FIRST) Closure<Result> request) {
Fluent<Result, Progress> task = new Fluent<Result, Progress>()
return new FluentAsyncTaskBuilder<Result, Progress>(task).from(request)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment