I sometimes find myself in a situation where I have some Stream[X]
, and a function X => Future Y
, that I'd like to combine to a Future[Stream[Y]]
, and I can't seem to find a way to do it. For example, I have
val x = (1 until 10).toStream
def toFutureString(value : Integer) = Future(value toString)
val result : Future[Stream[String]] = ???
I tried
val result = Future.Traverse(x, toFutureString)
which gives the correct result, but seems to consume the entire stream before returning the Future, which more or less defeats the purpse
I tried
val result = x.flatMap(toFutureString)
but that doesn't compile with type mismatch; found : scala.concurrent.Future[String] required: scala.collection.GenTraversableOnce[?]
val result = x.map(toFutureString)
returns the somewhat odd and useless Stream[Future[String]]
What should I do here to get things fixed?
Edit: I'm not stuck on a Stream
, I'd be equally happy with the same operation on an Iterator
, as long as it won't block on evaluating all items before starting to process the head
Edit2: I'm not 100% sure that the Future.Traverse construct needs to traverse the entire stream before returning a Future[Stream], but I think it does. If it doesn't, that's a fine answer in itself.
Edit3: I also don't need the result to be in order, I'm fine with the stream or iterator returned being whatever order.
[Future[Stream[String]]
, but I don't know how and when each evaluation should take place (if I did, I wouldn't be asking ;). In my mind a thunk and a Future are (possibly erraniously) similar things, so I would like to join or compose them I guess? – Martijn