![](/img/trans.png)
[英]Scala, ZIO - convert Future into ZIO or ZIO into Future. Is it possible?
[英]Scala, ZIO - convert Future[Either[...]] into ZIO
我有一个返回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
吗? 该主题中的文档不清楚。
我根本不使用 ZIO,但是:签名(在代码或 scaladoc 中)在这个主题上似乎相当清楚:
ZIO.fromFuture[A]
将Future[A]
转换为ZIO[Any, Throwable, A]
。
您传入Future[Either[Throwable, MyValue]]
,因此它将返回ZIO[Any, Throwable, Either[Throwable, MyValue]]
- 而不是您的代码所期望的ZIO[Any, Throwable, MyValue]
。
要将您的Either
的Left
case 转移到ZIO
的“错误通道”,您有几个选择,例如:
将Future[Either[Throwable, MyValue]]
转换为Future[Throwable, 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.