结合彼此依赖的期货

Combining Futures dependent on each other

我正在使用 Scala 向 API(准确地说是 Play Framework 的 WS)发出 HTTP GET 请求,它以 JSON 响应看起来像;

{
  data: [
    {text: "Hello there", id: 1},
    {text: "Hello there again", id: 2}
  ],
  next_url: 'http://request-this-for-more.com/api?page=2' //optional
}

因此,返回的 JSON 中的 next_url 字段可能存在也可能不存在。

我的方法需要做的是从调用第一个 URL 开始,检查响应是否有 next_url,然后对其执行 GET。最后,我应该将响应中的所有 data 字段组合成所有数据字段的一个未来。当响应中没有 next_url 时我终止。

现在,以阻塞方式执行此操作更容易,但我不想那样做。解决此类问题的最佳方法是什么?

在 scalaz 的某个地方可能有一种方法可以做到这一点,但如果您不知道具体的解决方案,通常可以使用递归和 flatMap 构建一个。类似于:

//Assume we have an async fetch method that returns Result and Option of next Url
def fetch(url: Url): Future[(Result, Option[Url])] = ...

//Then we can define fetchAll with recursion:
def fetchAll(url: Url): Future[Vector[Result]] =
  fetch(url) flatMap {
    case (result, None) => Future.successful(Vector(result))
    case (result, Some(nextUrl)) =>
      fetchAll(nextUrl) map {results => result +: results}
  }

(请注意,每次调用都使用一个堆栈帧 - 如果您想执行数千次提取,那么我们需要更仔细地编写它,以便它是尾递归的)

the Future.flatMap method 存在这样的情况

假设你有这样的东西:

case class Data(...)
def getContent(url:String):Future[String]
def parseJson(source:String):Try[JsValue]
def getData(value: JsValue):Seq[Data]

JsValue 类型的方法受 play json library

启发
def \ (fieldName: String): JsValue
def as[T](implicit ...):T //probably throwing exception

你可以像

一样编写最终结果
def innerContent(url:String):Future[Seq[Data]] = for {
  first <- getContent(url)
  json <- Future.fromTry(parseJson(first))
  nextUrlAttempt = Try((json \ "next_url").as[String])
  dataAttempt = Try(getData(json \ "data"))
  data <- Future.fromTry(dataAttempt)
  result <- nextUrlAttempt match {
    case Success(nextUrl) => innerContent(nextUrl)
    case Failure(_) => Future.successful(Seq())
} yield data ++ result

另请查看针对像您这样的复杂异步流的库:

  1. play iteratees
  2. scalaz iteratees
  3. scalaz stream