While using monix.eval.Task or zio.Task, is there a simple way to convert Option of Task to Task of Option?
Asked
Active
Viewed 499 times
3
-
3Vice versa is not possible since it would need to evaluate the Task which breaks the whole idea. – Luis Miguel Mejía Suárez Jul 01 '21 at 14:50
-
1Thanks, I realized that I don't need vice versa and updated the question. – Karthik P Jul 02 '21 at 11:31
-
You should look up `Traversable`. This trait is exactly what is needed here. – Mark Saving Jul 02 '21 at 18:38
1 Answers
3
If you want a pure ZIO solution, you can use .foreach
with identity
:
val fx: Option[UIO[Int]] = Option(Task.effectTotal(42))
val res: UIO[Option[Int]] = ZIO.foreach(fx)(identity)
If you're also using cats
, the method you're looking for is called .sequence
.
import cats.implicits.toTraverseOps
import zio.interop.catz._
import zio.{Task, UIO}
val fx: Option[UIO[Int]] = Option(Task.effectTotal(42))
val res: UIO[Option[Int]] = fx.sequence
The other way around is not possible as one would need to materialize the Task
in order to be able to lift it into an Option[T]
.

Yuval Itzchakov
- 146,575
- 32
- 257
- 321