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

I want to use MongoDB Async Java Driver in a Play Framework 2 project, MongoDB Async Java Driver returns SingleResponseCallback. I do not know how to handle this result in Play controllers.

For example, how to return the score from the following code in the playback controller:

collection.count( new SingleResultCallback<Long>() { @Override public void onResult(final Long count, final Throwable t) { System.out.println(count); } }); 

How can I get the result of SingleResultCallback and then convert it to Promise? is this a good way? What is the best practice in such situations?

+5
source share
3 answers

You must decide the promise yourself. Remember that Play promises are shells for scala futures and that the only way to decide the future is to use scala promises (different from play promises) (I know this is a bit confusing). You will need 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()); 

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

+2
source

Thanks @caeus answer, These are 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(); } 
0
source

A better 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())); } 
0
source

All Articles