Futuroid is an Android library that allows running asynchronous tasks and attaching callbacks thanks to a convenient syntax. It offers an alternative to the Android AsyncTask class.
- Future-based API (similar to Guava's ListenableFutures, Scala/Akka Futures, Javascript promises...)
- Allows registering callbacks to be run on the Android UI/main thread
- Provides a default ExecutorService (fixed thread pool with 5 threads) that can be replaced by a custom one
- Each task can be run on the default ExecutorService or on a custom one
- Allows task chaining (monad-style)
Image download asynchronous service:
public class DownloadService {
/**
* Downloads an image asynchronously.
*/
public Future<Bitmap> downloadImage(String url) {
return Async.submit(new Callable<Bitmap>() {
@Override
public Bitmap call() {
Bitmap bitmap;
// HTTP request goes here...
return bitmap;
}
});
}
}
Client code:
// download an image from a URL
imageService.downloadImage(url).addCallback(new FutureCallback<Bitmap>() {
@Override
public void onSuccess(Bitmap bitmap) {
// display the image
imageView.setImageBitmap(bitmap);
}
@Override
public void onFailure(Throwable t) {
Log.e(TAG, "Unable to download image", t);
}
});
Futuroid is available on the Maven Central Repository.
Maven-based configuration:
<dependency>
<groupId>com.github.clemp6r.futuroid</groupId>
<artifactId>futuroid</artifactId>
<version>1.0.0</version>
</dependency>
Gradle-based configuration:
dependencies {
compile 'com.github.clemp6r.futuroid:futuroid:1.0.0'
}