Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 231
nam Avatar asked Apr 12 '18 15:04

nam


2 Answers

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(_ => ())
like image 157
Dmytro Mitin Avatar answered Oct 28 '22 08:10

Dmytro Mitin


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_
like image 13
Luka Jacobowitz Avatar answered Oct 28 '22 06:10

Luka Jacobowitz