Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions core-tests/shared/src/test/scala/zio/ScopedRefSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,18 @@ object ScopedRefSpec extends ZIOBaseSpec {
acquire <- counter.acquired
release <- counter.released
} yield assertTrue(acquire == 3 && release == 3)
} +
test("eager release") {
for {
ref <- Ref.make(0)
acquire = ZIO.acquireRelease {
ref.modify(n => if (n == 0) (ZIO.unit, 1) else (ZIO.dieMessage("die"), n)).flatten
} { _ =>
ref.update(_ - 1)
}
scopedRef <- ScopedRef.fromAcquire(acquire)
_ <- scopedRef.set(acquire)
} yield assertCompletes
}
}
)
Expand Down
13 changes: 7 additions & 6 deletions core/shared/src/main/scala/zio/ScopedRef.scala
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ trait ScopedRef[A] {
* Sets the value of this reference to the specified resourcefully-created
* value. Any resources associated with the old value will be released.
*
* This method will not return until either the reference is successfully
* changed to the new value, with old resources released, or until the attempt
* to acquire a new value fails.
* This method will not return until the old resources are released and either
* the reference is successfully changed to the new value or the attempt to
* acquire a new value fails.
*/
def set[R, E](acquire: ZIO[R with Scope, E, A])(implicit trace: Trace): ZIO[R, E, Unit]

Expand Down Expand Up @@ -84,12 +84,13 @@ object ScopedRef {
ref.modifyZIO { case (oldScope, a) =>
ZIO.uninterruptibleMask { restore =>
for {
_ <- oldScope.close(Exit.unit)
newScope <- Scope.make
exit <- restore(acquire.provideSomeEnvironment[R](_.add[Scope](newScope))).exit
exit <- restore(newScope.extend[R](acquire)).exit
result <- exit match {
case Exit.Failure(cause) =>
newScope.close(Exit.unit).ignore.as(ZIO.refailCause(cause) -> (oldScope -> a))
case Exit.Success(a) => oldScope.close(Exit.unit).ignore.as(ZIO.unit -> (newScope -> a))
newScope.close(Exit.unit).as(ZIO.refailCause(cause) -> (oldScope -> a))
case Exit.Success(a) => ZIO.succeed(ZIO.unit -> (newScope -> a))
}
} yield result
}
Expand Down