我有一个返回Future[Either[Throwable, MyValue]]的简单方法。现在我想把它转换成ZIO。我创造了:
def zioMethod(): ZIO[Any, Throwable, MyValue] =
ZIO.fromFuture {implicit ec =>
futureEitherMethod().flatMap { result =>
Future(result)
}
}但是,它并没有在没有跟踪的情况下工作:No implicit found for parameter trace: Trace。
因此,在我将Trace作为隐式添加之后,它仍然不能正常工作。还有其他方法将Future[Either[,]]转换为ZIO吗?文档在本主题中不清楚。
发布于 2022-09-16 15:41:56
在这个主题上,签名(代码中的签名或scaladoc中的签名)似乎相当清楚:
ZIO.fromFuture[A]将Future[A]转换为ZIO[Any, Throwable, A]。
传入一个Future[Either[Throwable, MyValue]],这样它就会返回一个ZIO[Any, Throwable, Either[Throwable, MyValue]] --而不是代码所期望的ZIO[Any, Throwable, MyValue]。
要将Left的Either案例传输到ZIO的“错误通道”,您有几个选项,例如:
将Future[Either[Throwable, MyValue]]转换为Future[MyValue],然后转换为ZIO:
def zioMethod(): ZIO[Any, Throwable, MyValue] =
ZIO.fromFuture { implicit ec =>
futureEitherMethod().flatMap {
case Right(myValue) => Future.successful(myValue)
case Left(throwable) => Future.failed(throwable)
}
}转换为ZIO[Any, Throwable, Either[Throwable, MyValue]],然后转换为ZIO[Any, Throwable, MyValue]
def zioMethod(): ZIO[Any, Throwable, MyValue] = {
val fromFuture: ZIO[Any, Throwable, Either[Throwable, MyValue]] =
ZIO.fromFuture { implicit ec =>
futureEitherMethod()
}
fromFuture.flatMap(ZIO.fromEither)
}顺便说一句:对我来说,这不会在代码中带来任何额外的执行:https://scastie.scala-lang.org/dRefNpH0SEO5aIjegV8RKw。
更新:替代(更多的习语?)解决方案正如@LMeyer在评论中指出的,也有ZIO.absolve,对我来说,这似乎更符合ZIO -惯用的方式(我自己对ZIO几乎没有经验):
ZIO.fromFuture { implicit ec =>
futureEitherMethod()
}.absolvehttps://stackoverflow.com/questions/73744238
复制相似问题