[英]Composing Multiple Futures and Option in Scala with ZIO
我剛剛開始評估 ZIO 以改進編程 model 和我的異步 Scala 代碼的性能。 在我的代碼庫中,我經常處理Future[Option[T]]
,到目前為止,我已經使用 Scalaz 的OptionT
monad 轉換器處理了這個問題。 現在我想用 ZIO 試試這個。
考慮兩個函數:
def foo: String => Future[Option[T]]
和def bar: T => Future[U]
我試過這樣的事情:
val t = for {
o: Option[Int] <- ZIO.fromFuture { implicit ec =>
foo("test")
}
i: Int <- ZIO.fromOption(o)
s: String <- ZIO.fromFuture { implicit ec =>
bar(i)
}
} yield s
根據我的 IDE,在這種情況下t
的類型是ZIO[Any, Any, String]
。 我不知道該怎么辦。
我想考慮三種可能性:
foo
生成Some
的“成功”案例,該 Some 可以與 value 上的其他函數組合foo
產生None
的情況我不確定如何使用 ZIO 在這種情況下解析這些可能性。 任何幫助表示贊賞。
ZIO.fromOption(o)
的類型是IO[Unit, A]
,即ZIO[Any, Unit, A]
,而ZIO.fromFuture
的類型是Task[A]
,即ZIO[Any, Throwable, A]
,正如Type Aliases所記錄的那樣。 因此類型不對齊
ZIO[Any, Unit, A]
ZIO[Any, Throwable, A]
嘗試mapError
將錯誤類型與Throwable
對齊,如下所示
for {
o <- ZIO.fromFuture { implicit ec => foo("test") }
i <- ZIO.fromOption(o).mapError(_ => new RuntimeException("boom"))
s <- ZIO.fromFuture { implicit ec => bar(i)}
} yield s
在這種情況下,有幾個運算符可以幫助您,基本上不是用fromOption
顯式解開Option
,我建議使用some
和asSomeError
的組合
val t: Task[Option[String]] = (for {
// This moves the `None` into the error channel
i: Int <- ZIO.fromFuture(implicit ec => foo("test")).some
// This wraps the error in a Some() so that the signature matches
s: String <- ZIO.fromFuture(implicit ec => bar(i)).asSomeError
} yield s).optional // Unwraps the None back into the value channel
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.