【问题标题】:Wait in tail recursion for future to complete在尾递归中等待未来完成
【发布时间】:2020-08-05 07:31:03
【问题描述】:

我想一次发送 1000 条记录,每批 500 条。一旦发送,我希望尾递归继续。 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)
}

【问题讨论】:

  • ListsFutures 在您需要批处理和并行性之类的东西时不是一个好主意。我建议你看看流媒体库,比如Akka Streamsfs2monixzio zstreams

标签: scala scala-collections tail-recursion


【解决方案1】:

我猜你想要的是同步使用未来。您可以使用 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.resultHow risky is it to call Await.result on db calls的信息

【讨论】:

    猜你喜欢
    • 2017-06-22
    • 2015-01-07
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 2019-04-20
    • 2020-07-05
    • 2021-06-26
    • 2014-11-11
    相关资源
    最近更新 更多