Future.sequence((0 to 100).map(_ => nextValue)).map(_.flatten)
用法:
scala> Future.sequence((0 to 100).map(_ => nextValue)).map(_.flatten)
res3: scala.concurrent.Future[scala.collection.immutable.IndexedSeq[Int]] = [email protected]
scala> Await.result(res3, duration.Duration.Inf)
res4: scala.collection.immutable.IndexedSeq[Int] = Vector(5, 4, 3, 0, 4, 6, 0, 8, 0, 0, 4, 6, 2, 7, 4, 9, 8, 8, 6, 9, 1, 4, 5, 5, 8, 2, 2, 7, 6, 0, 5, 6, 6, 5, 9, 6, 3, 5, 7, 1, 3, 2, 5, 3, 3, 1, 8, 4, 6, 7, 5, 1, 3, 5, 7, 4, 1, 5, 9, 4, 5, 0, 1, 8, 5, 0, 0, 7, 4, 2, 4, 2, 2, 0, 4, 1, 6, 3, 8, 2, 1, 3, 5, 5, 8, 3, 6, 1, 3, 2, 9, 4, 9, 4, 7, 5, 7, 8, 7, 9, 5, 2, 5, 0, 2, 5, 6, 8, 6, 2, 3, 2, 0, 8, 9, 3, 9, 2, 7, 5, 1, 7, 1, 1, 8, 6, 8, 0, 5, 5, 6, 0, 8, 8, 3, 6, 4, 2, 7, 1, 0, 3, 3, 3, 3, 2, 8, 7, 3, 3, 5, 1, 6, 3, 3, 7, 8, 9, 9, 9, 1, 9, 9, 8, 1, 1, 5, 8, 1, 1, 7, 6, 3, 2, 5, 0, 4, 3, 0, 9, 9, 1, 2, 0, 3, 6, 2, 6, 8, 6, 6, 3, 9, 7, 1, 3, 5, 9, 6, 5, 6, 2)
或用scalaz /貓:
//import scalaz._,Scalaz._
// --or--
//import cats.syntax.traverse._
//import cats.std.list._
//import cats.std.future._
(0 to 100).toList.traverseM(_ => nextValue)
Eplanation從here:
traverseM(f)爲equival要穿過(f).map(_。join),其中連接是 拼合的名稱。這是非常有用的一種 「揭 flatMap」:
如果你需要一些條件,仍需要保持異步,您可以使用FS2:
import fs2._
import fs2.util._
def nextValue: Task[List[Int]] = Task.delay{
import scala.util.Random
val num1 = Random.nextInt(10)
val num2 = Random.nextInt(10)
if(num1 > 5) List(num1,num2) else List()
}
Stream.repeatEval(nextValue).takeWhile(_.size > 0).runLog.map(_.flatten).unsafeRun
https://github.com/functional-streams-for-scala/fs2/blob/series/0.9/docs/guide.md
同樣可以實現與迭代:
貓:https://github.com/travisbrown/iteratee 或scalaz-iteratee包
一般來說,你可以用fold
,因爲它實際上是unfold
並且在斯卡拉爲展開沒有很好的支持標準庫的Stream
不能一概而論了一個單子/ ApplicativeFunctor(如不實現這個EnumeratorT
確實) - 您只能在每個展開步驟中通過執行Await.result
來檢查條件。
如果每個'Future'僅在前一個完成後啓動,那麼使用'Future'有什麼意義?你可以在單一的「未來」中包裹一個「摺疊」或「流」,當停止條件滿足時它會完成嗎? – jwvh