2

我想检查 Future[Seq[String]] 是否为空并且我正在使用

if(!Future.sequence(sortSeq).isEmpty){
//doSomething
}

但它给我带来了错误?

4

2 回答 2

3

我想的类型sortSeqFuture[Seq[String]],所以你不需要Future.sequence

您必须等待结果,Future然后检查结果是否为空:

import scala.concurrent.duration._
if(!Await.result(sortSeq.map{_.isEmpty}, 5.seconds){
  //doSomething
}

如果你可以doSomething在不同的线程中执行,你可以试试这个:

val someRusultFuture = sortSeq.map{ rs =>
  if(!rs.isEmpty){
    //doSomething
  }
}

但你必须等待someRusultFuture.

证明它有效:

scala> import concurrent.{Future, Await}
import concurrent.{Future, Await}

scala> import scala.concurrent.duration._
import scala.concurrent.duration._

scala> val sortSeq = Future{ Thread.sleep(10000); Seq("a") }
sortSeq: scala.concurrent.Future[Seq[String]] = scala.concurrent.impl.Promise$DefaultPromise@3592f7c6

scala> Await.result(sortSeq.map{_.isEmpty}, 11.seconds)
res1: Boolean = false
于 2013-04-04T05:28:51.450 回答
0

Future.sequence方法用于将 aTraversableOnce[Future[A]]转换为 a Future[TraversableOnce[A]]

我认为您可以忘记是否Seq为空,只需Seq使用以下map功能即可Future

  val s = Future[Seq[String]](Seq("s", "e", "q"))
  val p  = s.map(s => s.foreach(println))

这是有效的,因为空检查是在后台隐式执行的。在下面的示例中,当Seq为空时,不会打印任何内容。

scala>   val s = Future[Seq[String]](Seq.empty)
s: scala.concurrent.Future[Seq[String]] = Future(<not completed>)

scala>   val p  = s.map(s => s.foreach(println))
p: scala.concurrent.Future[Unit] = Future(<not completed>)

如果你真的想进行空检查,你也可以使用withFilter.

带非空Seq

scala>   val s = Future[Seq[String]](Seq("s", "e", "q"))
s: scala.concurrent.Future[Seq[String]] = Future(Success(List(s, e, q)))

scala>   val p  = s.withFilter(_.nonEmpty).map(s => s.foreach(println))
p: scala.concurrent.Future[Unit] = Future(<not completed>)

s
e
q

带着一个空Seq

scala>   val s = Future[Seq[String]](Seq.empty)
s: scala.concurrent.Future[Seq[String]] = Future(Success(List()))

scala>   val p  = s.withFilter(_.nonEmpty).map(s => s.foreach(println))
p: scala.concurrent.Future[Unit] = Future(<not completed>)

您也可以按照上面的答案进行空检查

val someRusultFuture = sortSeq.map{ rs =>
  if(!rs.isEmpty){
    //doSomething
  }
}

希望这可以帮助。

于 2017-06-16T11:44:36.827 回答