Convert List[Task[List[A]]] to Task[List[A]]

785 Views Asked by At

How to convert List[Task[List[Header]]] type to Task[List[Header]] in scala .

I have a method which returns Task[List[Header]] and calling dor multiple times it becomes List[Task[List[Header]]]

2

There are 2 best solutions below

2
On BEST ANSWER

You can use Task.sequence, and then map flatten over the resulting list of lists, e.g:

val res: List[Task[List[Header]]] = ...
Task.sequence(res).map(_.flatten)

If you need parallel execution over the results, you can take a look on Task.gather.

0
On

That use case is covered by the function flatSequence: https://github.com/typelevel/cats/blob/v2.1.0/core/src/main/scala/cats/Traverse.scala#L86

As you can see it takes an F[G[F[A]] and turns it into a G[F[A]]. Now replace F with List and G with Task and you've got what you need. This will work for any F with a Traverse and FlatMap instance and any G with an Applicative instance.

If you want to run the tasks in parallel instead, you can use parFlatSequence found here: https://github.com/typelevel/cats/blob/v2.1.0/core/src/main/scala/cats/Parallel.scala#L155