【问题标题】:How do I turn a cats IO into a Effect using http4s如何使用 http4s 将猫 IO 变成 Effect
【发布时间】:2018-04-21 12:02:04
【问题描述】:

我有一些返回 IO 的代码,但我需要 http4s 中的 Effect。

import cats.effect.{Effect, IO}

class Service[F[_]: Effect] extends Http4sDsl[F] {
    val service: HttpService[F] = {
        HttpService[F] {
            case GET -> Root =>
                val data: IO[String] = getData()
                data.map(d => Ok(d))
        }
    }
}

给予

[error]  found   : cats.effect.IO[F[org.http4s.Response[F]]]
[error]  required: F[org.http4s.Response[F]]
[error]         data.map(d => Ok(d))
[error]                 ^

【问题讨论】:

  • F 在这里没有绑定到IO 有什么原因吗?含义HttpService[IO]?
  • 这就是http4s模板的做法。如果像HttpService[IO] 一样,它确实有效。我假设它可以保持抽象和更好的一些方法。也许不是。?

标签: scala scala-cats http4s


【解决方案1】:

我们可以使用具体的IO[A] 绕过的一种方法是使用LiftIO[F]

class Service[F[_]: Effect] extends Http4sDsl[F] {
  val service: HttpService[F] = {
    HttpService[F] {
      case GET -> Root =>
        getData().liftIO[F].flatMap(Ok(_))
    }
  }
}

LiftIO 电梯将提升:IO[A] => F[A],但这会产生我们F[F[Response[F]。为了编译,我们将在F 上使用flatten,因为由于我们的Effect 上下文边界要求,它在猫中有一个Monad(或FlatMap)实例。

如果我们想要更多细节,这是-Xprint:typer 结果:

cats.implicits.catsSyntaxFlatten[F, org.http4s.Response[F]](
   cats.effect.LiftIO.apply[F](Service.this.evidence$1)
                     .liftIO[F[org.http4s.Response[F]]](
                       data.map[F[org.http4s.Response[F]]](
                        ((d: String) => Service.this.http4sOkSyntax(Service.this.Ok)
                          .apply[String](d)(Service.this.evidence$1,
                                            Service.this.stringEncoder[F](
                                              Service.this.evidence$1, Service.this.stringEncoder$default$2[F]))))))(Service.this.evidence$1).flatten(Service.this.evidence$1)

而在世界末日,当你想给出具体的效果时,例如Service[IO],我们得到:

val serv: Service[cats.effect.IO] = 
  new Service[cats.effect.IO]()(effect.this.IO.ioConcurrentEffect)

其中ioConcurrentEffectEffect[IO] 实例。

似乎所有的好东西都定义在org.http4s.syntax.AllSyntax trait。

【讨论】:

  • 顺便说一句,liftIO 有语法扩展:getData().liftIO[F].flatMap(Ok(_))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-12
  • 2021-06-23
  • 1970-01-01
  • 2019-11-11
  • 2010-10-07
  • 2019-04-08
相关资源
最近更新 更多