3

While using monix.eval.Task or zio.Task, is there a simple way to convert Option of Task to Task of Option?

Karthik P
  • 481
  • 5
  • 9

1 Answers1

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