【问题标题】:How to use return value from function returning Future(Either[A, B]) in scala?如何在scala中使用返回Future(Either [A,B])的函数的返回值?
【发布时间】:2016-06-03 02:20:43
【问题描述】:

我有以下功能。

def get(id: Int): Future[Either[String, Item]] = {
    request(RequestBuilding.Get(s"/log/$id")).flatMap { response =>
      response.status match {
        case OK => Unmarshal(response.entity).to[Item].map(Right(_))
        case BadRequest => Future.successful(Left(s"Bad Request"))
        case _ => Unmarshal(response.entity).to[String].flatMap { entity =>
          val error = s"Request failed with status code ${response.status} and entity $entity"
          Future.failed(new IOException(error))
        }
      }
    }
  }

我正在尝试调用此函数,但我不确定如何知道它返回的是字符串还是项。以下是我失败的尝试。

Client.get(1).onComplete { result =>
        result match {
          case Left(msg) => println(msg)
          case Right(item) => // Do something
        }
      }

【问题讨论】:

    标签: scala future either


    【解决方案1】:

    onComplete 采用Try 类型的函数,因此您必须在Try 上进行双重匹配,并且在Either 成功的情况下

    Client.get(1).onComplete {
      case Success(either) => either match {
        case Left(int) => int
        case Right(string) => string
      }
      case Failure(f) => f
    }
    

    虽然绘制未来要容易得多:

    Client.get(1).map {
      case Left(msg) => println(msg)
      case Right(item) => // Do something
    }
    

    如果您想处理onCompleteFailure 部分,请在映射未来后使用recoverrecoverWith

    【讨论】:

    • onComplete 返回 Unit 而不是 Try。它接受一个具有Try 类型参数的函数。
    猜你喜欢
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 2019-02-09
    • 1970-01-01
    • 2017-08-02
    • 2022-12-09
    相关资源
    最近更新 更多