noncom
noncom

Reputation: 4992

Play Framework 2.1 + ReactiveMongo - populate multiple drop-down lists

I have a form with multiple drop-down lists that I create with select and options helpers in a template. Entities that should populate the lists are taken from the database. However, the retrieval from the database is asynchronous, so I should use Async in the action, as in this example. However, in my case, there is not a single find operation that I should wait on, but a Seq of Future objects, of unknown size. So how can I wait on multiple Future-s to prepare the lists before rendering the page? Or maybe there is some better way to do it?

Upvotes: 4

Views: 730

Answers (1)

coffeesnake
coffeesnake

Reputation: 1193

Scala futures would worth nothing if you wouldn't have a nice way to combine them.

If you have a sequence of future objects you can transform it into a future of sequence:

val futureList = Future.sequence(listOfFutures)

So now you have a single future to deal with. See the docs on Future companion object for a few other useful functions to combine futures in various ways.

If you're curious about other ways to play with futures (e.g. you can even combine them using a simple for-comprehansion due to their monadic nature) you might want to take a look at the primer on Scala futures for more insights.

Also if you're working with ReactiveMongo it would be definitely worth to take a look at the docs on Enumerator/Iteratee implementation of Play 2.x. If you master that approach you will be able to do real magic combining your reactive data streams on the fly and much more.

Upvotes: 7

Related Questions