How to use MongoDB Async Java Driver in Play Framework 2.x action? How to use MongoDB Async Java Driver in Play Framework 2.x action? mongodb mongodb

How to use MongoDB Async Java Driver in Play Framework 2.x action?


You have to resolve the promise yourself. Remember that the Play promises are wrappers to scala futures and that the only way to resolve a future is using scala Promises (different from play promises) (I know, it's kinda confusing). You'd have to do something like this:

Promise<Long> promise = Promise$.MODULE$.apply();collection.count( new SingleResultCallback<Long>() {   @Override   public void onResult(final Long count, final Throwable t) {     promise.success(count);  }});return F.Promise.wrap(promise.future());

That thing about the Promise$.MODULE$.apply() is just the way to access scala objects from java.


Thanks to @caeus answer, This is the details:

public F.Promise<Result> index() {    return F.Promise.wrap(calculateCount())            .map((Long response) -> ok(response.toString()));}private Future<Long> calculateCount() {    Promise<Long> promise = Promise$.MODULE$.apply();    collection.count(            new SingleResultCallback<Long>() {                @Override                public void onResult(final Long count, final Throwable t) {                    promise.success(count);                }            });    return promise.future();}


A cleaner solution would be to use F.RedeemablePromise<A>.

public F.Promise<Result> index() {    F.RedeemablePromise<Long> promise = F.RedeemablePromise.empty();    collection.count(new SingleResultCallback<Long>() {        @Override        public void onResult(final Long count, final Throwable t) {            promise.success(count);        }    });    return promise.map((Long response) -> ok(response.toString()));}