【问题标题】:Call a method that returns future n times调用返回未来 n 次的方法
【发布时间】:2020-07-14 05:57:27
【问题描述】:

我想调用一个方法 n 次。仅当前一个调用成功时,才应进行每个后续调用。此方法返回一个未来。我尝试的代码是这样的

    def doSomething: Future[R] = Future {
              //some logic 
              ???
    }

    def outer() = {
      val range = { 1 to 5 }

      def inner(range: Seq[Int]): Future[R]= 
        range.headOption match {
          case Some(head) =>
            doSomething.flatMap { _ => inner(range.tail)} 
          case None => ???
        }
      inner(range)
    }

如果没有,我想返回最后运行的未来的值。如何做到这一点?

【问题讨论】:

  • 我不得不问,如果你想同步期货,为什么要创建 N 个期货。为什么不把所有东西都搬过去?
  • 我有数据需要批量处理。每个批次都将由未来处理。

标签: scala future


【解决方案1】:

这样的?

// assumes that implicit ExecutionContext is available
// if it isn't available here add it to signature
def callMeNTimes[T](n: Int)(future: => Future[T]): Future[T] =
  if (n <= 0) Future.failed(new Exception("Cannot run future less that 1 times"))
  else if (n == 1) future
  else future.flatMap(_ => callMeNTimes(n-1)(future))

callMeNTimes(5)(doSomething)

如果您需要跨运行汇总结果,您可以执行以下操作:

def repeat[A](n: Int, init: A)(future: A => Future[A]): Future[A] =
  if (n <= 0) Future.successful(init)
  else future(init).flatMap(a => repeat(n-1, a)(future))

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2020-01-09
    • 2021-11-04
    • 1970-01-01
    相关资源
    最近更新 更多