等待尾递归以待将来完成

时间:2020-04-22 10:07:30

标签: scala scala-collections tail-recursion

我想以500个批处理一次发送1000条记录。一旦发送了它们,我希望尾部递归继续进行。 numberOfEventsPerSecond = 1000 putRecordLimit = 500 在Furure调用完成之前调用sendInBatches。有什么办法可以首先完成futureCall调用,然后仅调用sendInBatches。



  @scala.annotation.tailrec
  final def sendBatches(
    buffer: Seq[File],
    numberOfEventsPerSecond: Int
  ): Seq[PutRecordsRequestEntry] =
{
      val (listToSend, remaining) = buffer.splitAt(numberOfEventsPerSecond)
      val listRes = listToSend
        .grouped(putRecordLimit)
        .toList
        .filter(_.nonEmpty)

      listRes.map { list =>
        futureCall(list.filter(_ != null)) map { putDataResult =>
             println("Sent")
          )
        }
      }
      sendInBatches(fileOption, remaining, numberOfEventsPerSecond)
}

1 个答案:

答案 0 :(得分:0)

我想您想要的是同步使用Future。您可以使用Await.result(future,duration)进行此操作:

val future = futureCall(list.filter(_ != null))
val futureResult = Await.result(future, Duration.Inf)
sendInBatches(fileOption, remaining, numberOfEventsPerSecond)

仅在绝对必要时,应非常小心地使用Await.result。

有关期货的更多信息:https://docs.scala-lang.org/overviews/core/futures.html

有关为什么应避免使用Await.result How risky is it to call Await.result on db calls

的更多信息
相关问题