0

I have the below function.

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))
        }
      }
    }
  }

I am trying to call this function but I am not sure how to know whether it is returning a String or Item. Below is my failed attempt.

Client.get(1).onComplete { result =>
        result match {
          case Left(msg) => println(msg)
          case Right(item) => // Do something
        }
      }
Priya R
  • 451
  • 4
  • 14

1 Answers1

1

onComplete takes a function of type Try so you would have to double match on Try and in case of success on Either

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

much easier though would be to map the future:

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

and in case you want to handle the Failure part of onComplete use a recover or recoverWith after mapping on the future.

Ende Neu
  • 15,581
  • 5
  • 57
  • 68