Search code examples
scalataskscalazhttp4sfs2

fs2: Check for success of Seq(Task)


I have an asynchronous http4s client from which I get a collection of results, after running some requests. I want to check that this collection (a Seq[Task[Response]]) has finished for all Task objects, and that the Response objects are in a specific state.

If I were using Future instead of Task, I would do something like

val results: Seq[Future[Response]] = ...
Future.sequence(results).map(_.forall(_.customFunction.isSuccess))

Is there a way to achieve similar functionality using fs2.Task instead? In my limited understanding, I assume at some point I will have to call unsafeRun, which would block for each Task in the collection.


Solution

  • You could replace Future.sequence with something like:

    val results: Seq[Task[Response]] = ...
    val sequence: Task[Seq[Response]] = results.foldLeft(Task.now(Seq.empty[Response])) {
      (x, t) => x.flatMap(s => t.map(r => s :+ r))
    }
    

    Then do the success checking the same way.