javascalamonix

Scala Task return mapping


I have a method readHeader which takes one argument and returns Task[List[Header]] and another method calls for multiple ids and returns List[Task[List[EquipmentHeader]]]. How to make a return of Task[List[List[Header]]] compatible with multiple id read function.

trait M1{
  def readHeader(id: String): Task[List[Header]]
}

def read(ids: List[String])(implicit m1:M1):Task[List[List[Header]]] = {
    if (ids.isEmpty) {
      Task(List.empty)
    } else {
         ids.map(m1.readHeader(_)) //List[Task[List[Header]]]
    }
  }

Solution

  • You can use traverse from cats:

    import cats.implicits._
    
    ids.traverse(m1.readHeader) // Task[List[List[Header]]]