Is there sequential Future.find?

后端 未结 3 1497
春和景丽
春和景丽 2021-01-14 08:07

I have some side-effectful function,

def f(): Future[Int] = {
  val n = Random.nextInt()
  println(s\"Generated $n\")
  Future(n)
}

and I

3条回答
  •  轮回少年
    2021-01-14 08:43

    If I understand the question, then you will have to block the thread to proceed sequentially. You can use Await to accomplish that.

    scala> def f(): Future[Int] = {
     |   val n = Random.nextInt()
     |   println(s"Generated $n")
     |   Future(n)
     | }
    f: ()scala.concurrent.Future[Int]
    
    scala> def success(n: Int): Boolean = n % 2 == 0
    success: (n: Int)Boolean
    
    scala> val s = Stream.fill(10)(f)
    

    Using your way, I get

    scala> Future.find(s)(success) map println
    Generated 551866055
    Generated -561348666
    Generated -1103407834
    Generated -812310371
    Generated -1544170923
    Generated 2131361419
    Generated -236722325
    Generated -1473890302
    Generated -82395856
    Some(-561348666)
    res16: scala.concurrent.Future[Unit] = scala.concurrent.impl.Promise$DefaultPromise@15a2d71
    

    I should get answer as Some(-561348666), which you can get as

    scala> s.find(x => success(Await.result(x,1 seconds))).get onSuccess {case p=> println(p)}
    -561348666
    

提交回复
热议问题