![](/img/trans.png)
[英]Scala futures: what is the main thread expected to do while futures are executing?
[英]While Loop with Futures in Scala
我有兩種方法:
def getNextJob: Future[Option[Job]]
def process(job: Job): Future[Unit]
我想處理所有作業,直到沒有剩余作業為止。
我可以用Await
做到這一點,例如
private def process()(implicit ctx: ExecutionContext): Future[Unit] = {
var job: Option[Job] = Await.result(service.getNextJob, FiniteDuration(2, TimeUnit.SECONDS))
while(job.isDefined) {
Await.result(process(job.get), FiniteDuration(2, TimeUnit.SECONDS))
job = Await.result(service.getNextJob, FiniteDuration(2, TimeUnit.SECONDS))
}
Future.successful()
}
但這很丑陋,並且沒有正確使用 Futures。 有沒有辦法以某種方式鏈接期貨來代替它?
def go()(implicit ctx: ExecutionContext): Future[Unit] =
getNextJob.flatMap { maybeJob ⇒
if(maybeJob.isDefined) process(maybeJob.get).flatMap(_ ⇒ go())
else Future.unit
}
注意:它不是尾遞歸。
def processAll()(implicit ec: ExecutionContext): Future[Unit] =
getNextJob.flatMap {
case Some(job) => process(job).flatMap(_ => processAll())
case None => Future.unit
}
可能同時處理它們:
def processAll()(implicit ec: ExecutionContext): Future[Unit] =
getNextJob.flatMap {
case Some(job) => process(job).zipWith(processAll())((_,_) => ())
case None => Future.unit
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.