Karthik P
Karthik P

Reputation: 481

Is there a simple way to convert Option[Task[T]] to Task[Option[T]]?

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

Upvotes: 3

Views: 682

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

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].

Upvotes: 3

Related Questions