简体   繁体   English

Scala - 如何从 Hammock 中的 IO[HttpResponse] 获取数据?

[英]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.这是一个 http 客户端。 and json decoder:json解码器:

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]]]但是, result <- Sync[F].delay(decodeResponseEntity(res))行存在问题,因为我收到错误: Type mismatch. Reguired: IO[B_] but found F[Either[CodecException, List[GitRepository]]] 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.当我将unsafeRunSync()方法添加到retrieveRepositories(organization, params)时,它可以正常工作,但我应该在最后而不是在这里调用这个方法。 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.如果可以,您可能希望更改retrieveRepositories的定义并参数化效果类型( F ),而不是使用具体的IO类型。

If you can't change retrieveRepositories , add a implicit LiftIO constraint in getRepos .如果您无法更改retrieveRepositories ,请在getRepos中添加隐式LiftIO约束。 You will be able to use liftIO method to lift concrete IO values into F .您将能够使用liftIO方法将具体IO值提升到F An alternative would be use the Async typeclass, which inherits from both Sync and LiftIO .另一种方法是使用Async类型类,它继承自SyncLiftIO

See documentation for liftIO : https://typelevel.org/cats-effect/typeclasses/liftio.html请参阅liftIO文档: https://typelevel.org/cats-effect/typeclasses/liftio.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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