1 scala nested concurrent.futures
我想为我通过迭代器传递的每个元素顺序处理这个嵌套的期货。
我用 flatMap 和 Map 链接了期货,这是正确的方法吗?
在使用和不使用任何阻塞工具的情况下,我应该怎么做才能以所需的方式(如下所示)执行该过程?
object Main{
Iterator.foreach{e=>
process(e)
}
}
object A {
def doOne(e): Future[Any] = Future {
println("startFirst"); Thread.sleep(3000);
}
def doTwo(Any): Future[Any] = Future {
println("startSecond"); Thread.sleep(1000);
}
def doThree(Any): Future[Any] = Future {
println("do 3"); Thread.sleep(1000);
}
def doFour(e,Any): Future[Unit] = Future {
println(s"do 4&processComplete$e"); Thread.sleep(1000);
}
def process(e):Future[Unit]={
val a= doOne(e)
.flatMAp{a=> doTwo(a)}
.flatMap{b=>doThree(b)}
.map{c=> doFour(c)}
}
Run Code Online (Sandbox Code Playgroud)
如果我将 3 个元素 (e1,e2,e3) 传递给 def 进程,我希望程序打印:
startFirst (e1)
startSecond(e1)
startThree (e1)
startFour&processComplete (e1)
startFirst (e2)
startSecond(e2)
startThree (e2)
startFour&processComplete (e2)
startFirst (e3)
startSecond(e3)
startThree (e3)
startFour&processComplete (e3)
Run Code Online (Sandbox Code Playgroud)
代替:
startFirst (e1)
startFirst (e2)
startFirst (e3)
startSecond(e1)
startSecond(e2)
startSecond(e3)
startThree (e1)
startThree (e2)
startThree (e3)
startFour&processComplete (e1)
startFour&processComplete (e2)
startFour&processComplete (e3)
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
def sequentialTraverse_[A](col: IterableOnce[A])(f: A => Future[Any])(implicit ec: ExecutionContext): Future[Unit] =
col.iterator.foldLeft(Future.successful(())) {
case (accF, a) =>
accF.flatMap(_ => f(a)).map(_ => ())
}
Run Code Online (Sandbox Code Playgroud)
您也可以将其转换为扩展方法,以便您可以执行以下操作:
List("A", "B", "C").sequentialTraverse_(process)
Run Code Online (Sandbox Code Playgroud)
你可以看到它在这里工作。
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |