帮助我使用 ZLayers 定义一个 http4s。我正在学习,我很困惑。我想将 http 服务器作为一个组件。但我不知道如何组合 ZManageds 和 ZLayers 以便编译。
创建一个需要Runtime[ZEnv]
? ZEnv
或者创建一个需要 a 的层并为其生成运行时是否更有意义。
object HttpServer {
def createHttp4Server: ZManaged[Runtime[ZEnv], Throwable, Server] =
ZManaged.accessManaged { implicit runtime: Runtime[ZEnv] =>
BlazeServerBuilder[Task](runtime.platform.executor.asEC)
.bindHttp(8080, "localhost")
.withHttpApp(Routes.helloWorldService)
.resource
.toManagedZIO
}
def createHttp4Layer: ZLayer[RuntimeLayer, Throwable, Http4ServerLayer] =
ZLayer.succeed(createHttp4Server)
}
object Routes {
val helloWorldService = ...
}
package object simple {
type Http4ServerLayer = Has[ZManaged[Runtime[ZEnv], Throwable, Server]]
type RuntimeLayer = Has[Runtime[ZEnv]]
}
我不知道如何ZManaged[..., ..., Server]
从Layer
这里主要访问。我不完全理解这些access
方法。
object ItsAren extends App {
def run(args: List[String]): URIO[ZEnv, ExitCode] = {
val toProvide: ZIO[Http4ServerLayer, Nothing, ExitCode] =
ZIO
.accessM[Http4ServerLayer](_.get.useForever) //compile error
.as(ExitCode.success)
.catchAll(ZIO.succeed(ExitCode.failure))
val runtimeLayer: ZLayer[Any, Nothing, RuntimeLayer] = ZLayer.succeed(Runtime.default)
val http4Layer: ZLayer[RuntimeLayer, Throwable, Http4ServerLayer] = HttpServer.createHttp4Layer
val fullLayer: ZLayer[Any, Throwable, Http4ServerLayer] = runtimeLayer >>> http4Layer
val provided = toProvide.provideCustomLayer(fullLayer)
provided //compile error
}
}
type mismatch
found : ZIO[Runtime[ZEnv], Throwable, Nothing]
required: ZIO[Http4ServerLayer, ?, ?]
也在底部,但重要性较低
found : ZIO[ZEnv, Throwable, ExitCode]
required: URIO[ZEnv, ExitCode]
PR 中的相同内容,请随时发表评论 https://github.com/kovacshuni/itsaren/pull/1