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]]]
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]]]
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
You can use Task.sequence, and then map
flatten
over the resulting list of lists, e.g:If you need parallel execution over the results, you can take a look on
Task.gather
.