Skip to content

Instantly share code, notes, and snippets.

@dotcomputercraft
Last active October 29, 2018 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dotcomputercraft/eca493b5ed8f4775d2055b3f7b562f99 to your computer and use it in GitHub Desktop.
Save dotcomputercraft/eca493b5ed8f4775d2055b3f7b562f99 to your computer and use it in GitHub Desktop.
An Overview
The following adapter is inspired by mattiwintou adapter from Rx Observable to F.Promise
https://gist.github.com/matiwinnetou/7b69253acaad996747c4
1. Code reuse
- Future and CompletableFuture are part of Java 8 and thus ubiquitous
- F.Promise only exist within the Play Framework
- Using pure Java constructs means more flexible and compatibility with other frameworks
2. ReactiveX - Reactive Extensions
- Rx Observables work seamlessly with Future and CompletableFuture
public F.Promise<Result> rankedPairs() {
CompletableFuture cf = ...
return RxFutureAdapter.toPromise(cf).map(Controller::ok);
}
package util;
import play.libs.F;
import java.util.concurrent.CompletableFuture;
public class RxFutureAdapter<T> {
private final CompletableFuture<T> cf;
public RxFutureAdapter(final CompletableFuture<T> cf) {
this.cf = cf;
}
public static <E> F.Promise<E> toPromise(final CompletableFuture<E> obs) {
return new RxFuture(obs).adopt();
}
public F.Promise<T> adopt() {
F.RedeemablePromise<T> rPromise = F.RedeemablePromise.empty();
cf.whenCompleteAsync((res, err) -> {
if (err != null) {
rPromise.failure(err);
} else {
rPromise.success(res);
}
});
return rPromise;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment