在递归内添加项目到Future [List]

时间:2014-11-18 21:58:20

标签: scala recursion scala-collections

我在递归中遇到了Future List的问题。

当我在没有Futures的情况下实施此方法时,我使用了 ListBuffer ,然后将项目添加到列表中。

    val filtered = ListBuffer.empty[PostMD]
    filtered ++= postMd.filter(_.fromID == userID)

现在我试图用Futures实现它,但我找不到类似的解决方案
使用未来清单的最佳方式是什么。

 def getData(url: String, userID: String) = {

val filtered: (List[PostMD]) => Future[List[PostMD]] = Future[List[PostMD]]

def inner(url: String): Unit = {

  val chunk: Future[JsValue]  = BusinessLogic.Methods.getJsonValue(url)

  val postMd: Future[List[PostMD]] = for {
    x <- chunk.map(_.\("data").as[List[JsValue]])
    y <- x.map(_.\("data").as[PostMD])
  } yield y


  filtered = postMd.map(_.filter(_.fromID == userID))   // <- returned  Future[List[PostMD]]

  val next: String = (chunk.map(_.\("paging").\("next"))).toString

 if (next != null) inner(next)
}
inner(url)
filtered

 }

感谢,

三木

1 个答案:

答案 0 :(得分:0)

我尝试用随机数生成你想要的东西。

import scala.concurrent.{Await, Future}
import scala.util.Random

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._

val RANDOM = new Random()

def futureRec(num: Int, f: Future[List[Integer]]): Future[List[Integer]] = {
  if(num == 0) {
    f
  } else {
    f.flatMap(l => {
      futureRec(num - 1, Future.successful(RANDOM.nextInt() :: l))
    })
  }
}

val futureResult = futureRec(5, Future.successful(Nil))

Await.result(futureResult, 5 minutes)

所以我会这样做,你想要的是这样的东西:

def getData(url: String, userID: String):Future[List[PostMD]] = {
  def inner(url: String, f: Future[List[PostMD]]): Future[List[PostMD]] = {

      val chunk: Future[JsValue]  = ???
      chunk.flatMap(ch => {
        val postMd = (ch \ "data").\\("data").map(_.as[PostMD]).toList
        val relatedPostMd = postMd.filter(_.fromID == userID)
        val next: String = (ch.\("paging").\("next")).as[String]
        if (next != null)
           inner(next, f.map(l => l ++ relatedPostMd))
        else
           f.map(l => l ++ relatedPostMd)
      })
  }

  inner(url, Future.successful(Nil))
}