Scala序列连接

时间:2014-08-08 04:38:06

标签: scala scala-collections

我有以下代码:

  def getLists(token: String, username: String):Future[Try[Seq[Group]]] = {
    val result:Future[Try[JsValue]] = getAPIResult(token, "https://myapi.com/screen_name=" + username)
    result.map( x => convertFromJsValueToObject(x))
  }

  def getSubscriptions(token: String, username: String):Future[Try[Seq[Group]]] = {...} //same as above

  private def getAPIResult(token: String, apiCall: String):Future[Try[JsValue]] = {
    WS.url(apiCall)
    .withHeaders("Authorization" -> ("Bearer " + token))
    .get().map(response =>
       response.status match {
       case 200 => Success(Json.parse(response.body))
       case _ => Failure(new RuntimeException("Web service call failed: " + response.body))
    })
  }

  private def convertFromJsValueToObject(json: Try[JsValue]): Try[Seq[Group]] = {
    json match {
      case Success(v) => {
        Success(v.as[Seq[Group]])
      }
      case Failure(t) => Failure(t)
      }
  }

我有第三个这样的功能:

def getAllListsAndSubscriptions(token: String, username: String):Future[Try[Seq[Group]]] = {...}

应该将SeqGroup个对象集合在一起并根据类型签名返回它们。我真的很想弄清楚如何做到这一点,因为类型是如此深层嵌套。

我是否编写了严格的代码或有没有办法执行此操作?我也很感激你的解释,所以下次我遇到这样的事情时我不需要求帮助!

1 个答案:

答案 0 :(得分:0)

似乎没有必要在Try中拥有Future,因为两者都捕获了可能失败的操作的想法。如果你被困住会认为你可以压扁那些:

def getAllListsAndSubscriptions(token: String, username: String): Future[Try[Seq[Group]] =
  for {
    lists <- getLists(token, username).flatMap(Future.fromTry)
    subscriptions <- getSubscriptions(token, username).flatMap(Future.fromTry)
  } yield { lists ++ subscriptions }

或者:

def getAllListsAndSubscriptions(token: String, username: String): Future[Try[Seq[Group]] =
  val lists = getLists(token, username).flatMap(Future.fromTry)
  val subscriptions = getSubscriptions(token, username)).flatMap(Future.fromTry)
  Future.reduce(Seq(lists, subscriptions))( _ ++ _)

但理想情况下,Future[Try[_]]从一开始就不会逃避这些功能。