[英]How to wrap effectful F instead of the concrete type constructor?
I have the following function definition:我有以下 function 定义:
private val checkSapHealth: IO[ServerHealth] =
BlazeClientBuilder[IO](global).resource.use { client =>
discovery
.senderAddr
.flatMap { addr =>
client
.get(addr.url |+| addr.health) { res =>
res.status match {
case Ok =>
IO(ServerOnline)
case _ =>
IO(ServerOffline)
}
}
.timeout(2.second)
.recover {
case _: Throwable => ServerOffline
}
}
}
I would like to replace the concrete type IO
through F[_]
to make it more abstract.我想通过
F[_]
替换具体类型IO
使其更抽象。 The problem here is the line:这里的问题是:
IO(ServerOnline)
The question is how to make it to问题是如何做到
F(ServerOnline)
Try to use cats.effect.Sync
尝试使用
cats.effect.Sync
https://typelevel.org/cats-effect/typeclasses/sync.html https://typelevel.org/cats-effect/typeclasses/sync.html
So basically using
Sync[IO].delay
is equivalent to usingIO.apply
.所以基本上使用
Sync[IO].delay
相当于使用IO.apply
。
private def checkSapHealth[F[_]: Sync]: F[ServerHealth] = ...
use ConcurrentEffect and add an implicit Applicative of F, thus giving you the option to lift values into the F context使用ConcurrentEffect并添加 F 的隐式 Applicative,从而使您可以选择将值提升到 F 上下文中
private def checkSapHealth[F[_] : ConcurrentEffect](implicit A: Applicative[F]): F[ServerHealth] =
BlazeClientBuilder[F](global).resource.use { client =>
discovery
.senderAddr
.flatMap { addr =>
client
.get(addr.url |+| addr.health) { res =>
res.status match {
case Ok =>
A.pure(ServerOnline)
case _ =>
A.pure(ServerOffline)
}
}
.timeout(2.second)
.recover {
case _: Throwable => ServerOffline
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.