Search code examples
scalafunctional-programmingscala-catsmonix

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


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


Solution

  • 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.