How to create an Enumerator [T] specified by Enumerator [Future [T]]

I'm trying to get the Iteratee library on Play 2.2.x. I am writing a function that generates a data stream that is expensive to compute. Here is the basic idea that replaced the expensive computing part with a square:

def expensiveFunction(x: Int): Future[Int] = Future.successful(x * x) def expensiveRange(start: Int, end: Int): Enumerator[Future[Int]] = { Enumerator.enumerate(start to end).map(i => expensiveFunction(i)) } 

If I call expensiveRange , I get Enumerator[Future[Int]] , which is not what I want, since it does not seem to use the explicit asynchrony of the Iteratee template. It seems I would have to convert this to Enumerator[Int] , which under the covers uses the futures that I return, instead of creating another level of Future .

Do I understand correctly that converting the result to Enumerator[Int] desirable? If so, what is the idiomatic way to do this?

+6
source share
1 answer

You can convert Enumerator[Future[Int]] to Enumerator[Int] as follows:

 val enumF = Enumerator((1 to 10).map{Future(_)}:_*) // Enumerator[Future[Int]] val enum = enumF &> Enumeratee.mapM(identity) // Enumerator[Int] 

But you do not need this conversion, as Travis Brown noted that you can rewrite your method as follows:

 def expensiveRange(start: Int, end: Int): Enumerator[Int] = { Enumerator.enumerate(start to end) &> Enumeratee.mapM(expensiveFunction) } 
+13
source

All Articles