Skip to content

Commit

Permalink
Maintain freshness of the ZLayer (zio#8870)
Browse files Browse the repository at this point in the history
  • Loading branch information
kpritam authored May 19, 2024
1 parent 08d157c commit b9f54f5
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
17 changes: 17 additions & 0 deletions core-tests/shared/src/test/scala/zio/ZLayerSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,23 @@ object ZLayerSpec extends ZIOBaseSpec {
result <- ref.get
} yield assert(result)(hasSize(equalTo(8)))
} @@ nonFlaky,
test("fresh with combination of other operators maintains freshness") {
def makeLayer1(ref: Ref[Vector[String]]): ZLayer[Any, Nothing, Service1] = ZLayer {
ref.update(_ :+ "1").as(new Service1 {})
}
def makeLayer2(ref: Ref[Vector[String]]): ZLayer[Service1, Nothing, Service2] = ZLayer {
(ZIO.service[Service1] *> ref.update(_ :+ "2")).as(new Service2 {})
}

for {
ref <- makeRef
layer1 = makeLayer1(ref)
layer2 = makeLayer2(ref)
_ <- (ZIO.service[Service1] *> ZIO.service[Service2])
.provide(layer1.fresh.map(identity).update(a => a), layer2)
result <- ref.get
} yield assert(result)(hasSameElements(Vector("1", "1", "2")))
} @@ nonFlaky,
test("preserves identity of acquired resources") {
for {
testRef <- Ref.make(Vector[String]())
Expand Down
6 changes: 4 additions & 2 deletions core/shared/src/main/scala/zio/ZLayer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -211,8 +211,10 @@ sealed abstract class ZLayer[-RIn, +E, +ROut] { self =>
final def foldCauseLayer[E1, RIn1 <: RIn, ROut2](
failure: Cause[E] => ZLayer[RIn1, E1, ROut2],
success: ZEnvironment[ROut] => ZLayer[RIn1, E1, ROut2]
)(implicit ev: CanFail[E]): ZLayer[RIn1, E1, ROut2] =
ZLayer.Fold(self, failure, success)
)(implicit ev: CanFail[E]): ZLayer[RIn1, E1, ROut2] = {
val foldLayer = ZLayer.Fold(self, failure, success)
if (isFresh) ZLayer.Fresh(foldLayer) else foldLayer
}

/**
* Creates a fresh version of this layer that will not be shared.
Expand Down

0 comments on commit b9f54f5

Please sign in to comment.