如何一次又一次地调用方法,直到它返回包含`None`的`Future`值

时间:2014-10-13 21:40:47

标签: scala future

给定一个返回Future的方法......

def remove(id: String): Future[Option[User]] = Future {
  // removes and returns the user identified by `id`
}

...如何一次又一次地调用它,直到它返回包含Future的{​​{1}}值?

修改

也许值得一提的是,我不需要收集结果。我只需要找到要删除的用户就可以调用该方法。我们的想法是Noneloop返回remove时停止。

3 个答案:

答案 0 :(得分:4)

之前有人评论说没有意义。

让我感到意外的是,懒散地消费期货并不是一件容易的事。 Future.findfirstCompletedOf类似,但并不代表find first in traversable order

scala> import concurrent._, ExecutionContext.Implicits._
import concurrent._
import ExecutionContext.Implicits._

scala> import java.util.concurrent.atomic._
import java.util.concurrent.atomic._

scala> val count = new AtomicInteger(10)
count: java.util.concurrent.atomic.AtomicInteger = 10

scala> def f(s: String) = Future { if (count.decrementAndGet <= 0) None else Some(s) }
f: (s: String)scala.concurrent.Future[Option[String]]

scala> def g(ss: List[String]): Future[List[String]] = f("hello") flatMap { case None => Future.successful(ss) case Some(s) => g(s :: ss) }
g: (ss: List[String])scala.concurrent.Future[List[String]]

scala> g(Nil)
res0: scala.concurrent.Future[List[String]] = scala.concurrent.impl.Promise$DefaultPromise@65a15628

scala> .value
res1: Option[scala.util.Try[List[String]]] = Some(Success(List(hello, hello, hello, hello, hello, hello, hello, hello, hello)))

说明不阻止的效用:

scala> :pa
// Entering paste mode (ctrl-D to finish)

import scala.util._
import concurrent._, ExecutionContext.Implicits._
import java.util.concurrent.atomic._

class Work {
  val count = new AtomicInteger(10)
  def f(s: String) = Future {
    if (count.decrementAndGet <= 0) None else Some(s)
  } andThen {
    case Success(Some(x)) => Console println s"Calculated $x"
    case Success(None)    => Console println "Done."
    case _                => Console println "Failed."
  }
}

// Exiting paste mode, now interpreting.

import scala.util._
import concurrent._
import ExecutionContext.Implicits._
import java.util.concurrent.atomic._
defined class Work

显示Stream版本,在消费线程逐步执行阻止之前不会计算前缀等待:

scala> val work = new Work
work: Work = Work@1b45c0e

scala> Stream continually work.f("hello") takeWhile { x => Await.result(x, duration.Duration.Inf).nonEmpty }
Calculated hello
res0: scala.collection.immutable.Stream[scala.concurrent.Future[Option[String]]] = Stream(scala.concurrent.impl.Promise$DefaultPromise@66629f63, ?)

scala> .toList
Calculated hello
Calculated hello
Calculated hello
Calculated hello
Calculated hello
Calculated hello
Calculated hello
Calculated hello
Done.
res1: List[scala.concurrent.Future[Option[String]]] = List(scala.concurrent.impl.Promise$DefaultPromise@66629f63, scala.concurrent.impl.Promise$DefaultPromise@610db97e, scala.concurrent.impl.Promise$DefaultPromise@6f0628de, scala.concurrent.impl.Promise$DefaultPromise@3fabf088, scala.concurrent.impl.Promise$DefaultPromise@1e392345, scala.concurrent.impl.Promise$DefaultPromise@12f3afb5, scala.concurrent.impl.Promise$DefaultPromise@4ced35ed, scala.concurrent.impl.Promise$DefaultPromise@2c22a348, scala.concurrent.impl.Promise$DefaultPromise@7bd69e82)

scala> .foreach (Console println _.value.get)
Success(Some(hello))
Success(Some(hello))
[snip]

其他行为,可能更合适,你得到一个包含计算前缀结果的Future:

scala> :pa
// Entering paste mode (ctrl-D to finish)

  val work = new Work
  def g(ss: List[String]): Future[List[String]] = work.f("hello") flatMap {
    case None => Future.successful(ss)
    case Some(s) => g(s :: ss)
  }

// Exiting paste mode, now interpreting.

work: Work = Work@796d3c9f
g: (ss: List[String])scala.concurrent.Future[List[String]]

scala> g(Nil)
Calculated hello
Calculated hello
res3: scala.concurrent.Future[List[String]] = scala.concurrent.impl.Promise$DefaultPromise@99a78d7
Calculated hello
Calculated hello
Calculated hello

scala> Calculated hello
Calculated hello
Calculated hello
Calculated hello
Done.

使用未来:

scala> .value
res5: Option[scala.util.Try[List[String]]] = Some(Success(List(hello, hello, hello, hello, hello, hello, hello, hello, hello)))

答案 1 :(得分:0)

Stream#continually无休止地做同样的事情,Stream#takeWhile在某个时刻停止它。 http://www.scala-lang.org/api/2.11.0/index.html#scala.collection.immutable.Stream

Stream.continually(/*remove*/).takeWhile(/*not Future[None]*/)

答案 2 :(得分:0)

这是:

import concurrent._, ExecutionContext.Implicits._
import java.util.concurrent.atomic._

val count = new AtomicInteger(10)

def f(s: String) = Future {
  if (count.decrementAndGet <= 0) None else Some(s)
}

Iterator continually {
  f("hello")
} takeWhile {
  Await.result(_, duration.Duration.Inf).nonEmpty
} foreach { _.map { _.map {
  println
}}

我希望它有所帮助。