A ZIO 2 collectAllPar example using Scala 3

As a brief note today, if you want to see an example of the ZIO collectAllPar method, the Scala 3 source code below shows one possible example that uses collectAllPar in a for expression.

First, here’s a small snippet of code that shows just the key parts:

def runSlowly(i: Int): UIO[Int] = ZIO.succeed { sleep(1_000); i }

object ZioCollectAllPar extends ZIOAppDefault:

    override def run =

        val a = runSlowly(10)
        val b = runSlowly(20)
        val c = runSlowly(30)

        val rez = ZIO.collectAllPar( List(a, b, c) )

        for 
            a <- rez
        yield
            a.sum

Next, here’s the complete ZIO collectAllPar example, including some initial setup code that shows everything you need to run the example using Scala-CLI:

//> using scala "3"
//> using lib "dev.zio::zio::2.0.19"

// Set up your IDE:
//     scala-cli setup-ide .
// Run me like this:
//     scala-cli ThisFilename.scala

import Thread.sleep
import java.time.{Instant, Duration => JDuration}

import zio.{durationInt, Duration, UIO, ZIO, ZIOAppDefault}

// you can use the complete ZIO or the UIO alias:
// def runSlowly(i: Int): ZIO[Any, Nothing, Int] = ZIO.succeed{ sleep(500); 1 }
def runSlowly(i: Int): UIO[Int] = ZIO.succeed { 
    sleep(1_000)
    i 
}

object ZioCollectAllPar extends ZIOAppDefault:

    override def run =

        val start = Instant.now

        val a = runSlowly(10)
        val b = runSlowly(20)
        val c = runSlowly(30)

        // you can declare the complete ZIO type here, or not:
        // val rez: ZIO[Any, Nothing, List[Int]] = ZIO.collectAllPar( List(a, b, c) )
        // note: can just move `ZIO.collectAllPar` inside the `for` expression.
        val rez = ZIO.collectAllPar( List(a, b, c) )

        for 
            a <- rez
        yield
            val stop = Instant.now
            val delta = JDuration.between(start, stop)
            println(s"delta = ${delta.toMillis / 1000.0} seconds")
            println(s"SUM: ${a.sum}")

As mentioned, in that code I handle the collectAllPar result in a for expression, but depending on your needs and data, there are other ways to handle the result, including map, fold, and more.

Finally, if you name that file ZioCollectAllPar.scala and run it with this scala-cli command:

scala-cli ZioCollectAllPar.scala

you should see this result:

delta = 1.049 seconds
SUM: 60

A key here is that this code shows how to run three instances of the runSlowly function in parallel using collectAllPar.