Skip to content

Commit

Permalink
suspend effects (#3444)
Browse files Browse the repository at this point in the history
  • Loading branch information
adamgfraser committed Apr 25, 2020
1 parent b38f718 commit 5370e53
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
9 changes: 9 additions & 0 deletions core-tests/shared/src/test/scala/zio/ZIOSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,15 @@ object ZIOSpec extends ZIOBaseSpec {
val list = List(1, 2, 3).map(IO.effectTotal[Int](_))
val res = IO.collectAllPar(list)
assertM(res)(equalTo(List(1, 2, 3)))
},
testM("is referentially transparent") {
for {
counter <- Ref.make(0)
op = counter.getAndUpdate(_ + 1)
ops3 = ZIO.collectAllPar(List(op, op, op))
ops6 = ops3.zipPar(ops3)
res <- ops6
} yield assert(res._1)(not(equalTo(res._2)))
}
),
suite("collectAllParN")(
Expand Down
22 changes: 10 additions & 12 deletions core/shared/src/main/scala/zio/ZIO.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@

package zio

import java.util.concurrent.atomic.AtomicReferenceArray

import scala.concurrent.ExecutionContext
import scala.reflect.ClassTag
import scala.util.{ Failure, Success }
Expand Down Expand Up @@ -2588,17 +2586,17 @@ object ZIO extends ZIOCompanionPlatformSpecific {
*
* For a sequential version of this method, see `foreach`.
*/
def foreachPar[R, E, A, B](as: Iterable[A])(fn: A => ZIO[R, E, B]): ZIO[R, E, List[B]] = {
val size = as.size
val resultArr = new AtomicReferenceArray[B](size)

val wrappedFn: ZIOFn1[(A, Int), ZIO[R, E, Any]] = ZIOFn(fn) {
case (a, i) => fn(a).tap(b => ZIO.effectTotal(resultArr.set(i, b)))
def foreachPar[R, E, A, B](as: Iterable[A])(f: A => ZIO[R, E, B]): ZIO[R, E, List[B]] = {
val size = as.size
effectTotal(Array.ofDim[AnyRef](size)).flatMap { array =>
val zioFunction: ZIOFn1[(A, Int), ZIO[R, E, Any]] =
ZIOFn(f) {
case (a, i) =>
f(a).flatMap(b => effectTotal(array(i) = b.asInstanceOf[AnyRef]))
}
foreachPar_(as.zipWithIndex)(zioFunction) *>
effectTotal(array.asInstanceOf[Array[B]].toList)
}

foreachPar_(as.zipWithIndex)(wrappedFn).as(
(0 until size).reverse.foldLeft[List[B]](Nil)((acc, i) => resultArr.get(i) :: acc)
)
}

/**
Expand Down

0 comments on commit 5370e53

Please sign in to comment.