Developus
Developus

Reputation: 1462

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]]]. 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?

Upvotes: 0

Views: 83

Answers (1)

Haemin Yoo
Haemin Yoo

Reputation: 541

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

Upvotes: 1

Related Questions