1 回答
TA贡献1880条经验 获得超4个赞
这是如何完成的草图(未经测试;我不声称这是最好的解决方案):
// I assume that the Web/Image/Video functions return instances of Future[Result]
val f1 = Web(query)
val f2 = Image(query)
val f3 = Video(query)
val t = timeout(80.milliseconds)
// using Scala's Future API
val results: Future[Seq[Result]] = for {
r1 <- or(f1)(t)
r2 <- or(f2)(t)
r3 <- or(f3)(t)
} yield (r1.toSeq ++ r2.toSeq ++ r3.toSeq)
// OR using async
val results: Future[Seq[Result]] = async {
val r1 = or(f1)(t)
val r2 = or(f2)(t)
val r3 = or(f3)(t)
await(r1).toSeq ++ await(r2).toSeq ++ await(r3).toSeq
}
// or and timeout are utility/library functions defined below
def or[T](f1: Future[T])(f2: Future[Option[Nothing]]): Future[Option[T]] =
Future.firstCompletedOf(f1 map Some.apply, f2)
// create a future that will complete successfully with None
// after the given duration passes
def timeout(d: Duration): Future[Option[Nothing]] = {
val p = Promise[Option[Nothing]]
Scheduler.after(d) { p success None }
p.future
}
- 1 回答
- 0 关注
- 177 浏览
添加回答
举报