简体   繁体   中英

Scala - how to get data from IO[HttpResponse] in Hammock?

I have a simple methods:

def retrieveRepositories(url: String, params: String): IO[HttpResponse] = Hammock.getWithOpts(uri"$url", createOpts).exec[IO]

Which is a http client. and json decoder:

implicit def decodeResponseEntity(response: HttpResponse): Either[CodecException, List[GitRepository]] = Decoder[List[GitRepository]].decode(response.entity)

Now I want to call this client like this:

def getRepos(organization: String, params: String): F[Either[CodecException, List[GitRepository]]] = for {
    res <- retrieveRepositories(organization, params)
    result <- Sync[F].delay(decodeResponseEntity(res))
  } yield result

But, there is a problem with result <- Sync[F].delay(decodeResponseEntity(res)) line, because I got an error: Type mismatch. Reguired: IO[B_] but found F[Either[CodecException, List[GitRepository]]] Type mismatch. Reguired: IO[B_] but found F[Either[CodecException, List[GitRepository]]] . When I add unsafeRunSync() method to retrieveRepositories(organization, params) then it works ok, but I should call this method in the end and not here. How should I fix it?

If you can, you may want to change the definition of retrieveRepositories and parameterize on the effect type ( F ) instead of using the concrete IO type.

If you can't change retrieveRepositories , add a implicit LiftIO constraint in getRepos . You will be able to use liftIO method to lift concrete IO values into F . An alternative would be use the Async typeclass, which inherits from both Sync and LiftIO .

See documentation for liftIO : https://typelevel.org/cats-effect/typeclasses/liftio.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM