18

I created a list of IO[Unit] in order to retrieve data from a list of URL. But now how I convert it back to a single IO[Unit] ?

nam
  • 3,542
  • 9
  • 46
  • 68

2 Answers2

33

You can do this in the following way

val x: List[IO[Unit]] = ???

import cats.implicits._

val y: IO[List[Unit]] = x.sequence

val z: IO[Unit] = y.map(_ => ())
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
  • 4
    Also, you can substitute `.map(_ => ())` with `.void` (though `sequence_` mentioned below is shorter). see the [scaladoc](https://typelevel.org/cats/api/cats/Functor.html#void[A](fa:F[A]):F[Unit]) – Haemin Yoo Oct 16 '18 at 05:25
16

This is just in addition to what Dmytro already said, you can actually do it in a single step by using traverse_ or sequence_. Both of these are really useful if you just don't care about the result. Code would look like this:

import cats.implicits._

val x: List[IO[Unit]] = ???

val y: IO[Unit] = x.sequence_
Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57