如何使用http4s将cat IO转换为效果

Ste*_*hen 3 scala scala-cats http4s

我有一些返回IO的代码,但是我需要在http4s中使用效果。

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))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Yuv*_*kov 5

我们可以使用混凝土解决问题的一种方法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(_))
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

LiftIO升降机将升降机:IO[A] => F[A],但这使我们受益F[F[Response[F]。为了编译内容,我们会继续进行flatten下去,F因为由于我们的上下文范围要求,它在cats中有一个Monad(或FlatMap)实例Effect

如果我们想要更多细节,这是-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)
Run Code Online (Sandbox Code Playgroud)

而在世界尽头,例如Service[IO],您想要给出具体效果时,我们得到:

val serv: Service[cats.effect.IO] = 
  new Service[cats.effect.IO]()(effect.this.IO.ioConcurrentEffect)
Run Code Online (Sandbox Code Playgroud)

哪里ioConcurrentEffectEffect[IO]实例。

似乎所有的好东西都定义为org.http4s.syntax.AllSyntax特质。