nam
nam

Reputation: 3632

cats-effect: How to transform `List[IO]` to `IO[List]`

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

Upvotes: 18

Views: 10504

Answers (2)

Luka Jacobowitz
Luka Jacobowitz

Reputation: 23502

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_

Upvotes: 17

Dmytro Mitin
Dmytro Mitin

Reputation: 51658

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(_ => ())

Upvotes: 34

Related Questions