Skip to content

Instantly share code, notes, and snippets.

@kdrakon
Created May 9, 2019 00:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kdrakon/f16958d2d7ad5e215274bc8ea5323d18 to your computer and use it in GitHub Desktop.
Save kdrakon/f16958d2d7ad5e215274bc8ea5323d18 to your computer and use it in GitHub Desktop.
Short-circuit a list of Cats Effect (IO) using a foldLeft
object Main extends App {
val l = List(IO(println(1).asRight), IO(println(2).asRight), IO("foo".asLeft), IO(println(4).asRight))
val io = l.foldLeft[IO[Either[String, Unit]]](IO(Right(())))((prev, next) => {
prev.flatMap({
case Left(err) => IO(Left(err))
case Right(_) => next
})
})
println(io.unsafeRunSync())
// will print:
// 1
// 2
// Left(foo)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment