Skip to content
Closed
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
25 changes: 25 additions & 0 deletions core/shared/src/main/scala/cats/effect/IOLocal.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package cats.effect

import cats.syntax.functor._

/**
* [[IOLocal]] provides a handy way of manipulating a context on different scopes.
*
Expand Down Expand Up @@ -188,6 +190,27 @@ sealed trait IOLocal[A] {
*/
def getAndReset: IO[A]

/**
* Creates a scope with the given value. The original value is restored upon the finalization
* of a resource. It means all changes made inside of the resource will not be propagated to
* the outside.
*
* @example
*
* {{{
* for {
* local <- IOLocal(42)
* _ <- local.get // returns 42
* _ <- local.scope(0).surround(local.getAndSet(1)) // returns 0
* _ <- local.get // returns 42, even though 1 was set inside of the resource
* } yield ()
* }}}
*
* @param value
* the value to make a scope with
*/
def scope(value: A): Resource[IO, Unit]

}

object IOLocal {
Expand Down Expand Up @@ -230,6 +253,8 @@ object IOLocal {
override def getAndReset: IO[A] =
get <* reset

override def scope(value: A): Resource[IO, Unit] =
Resource.make(getAndSet(value))(p => set(p)).void
}
}

Expand Down
10 changes: 10 additions & 0 deletions tests/shared/src/test/scala/cats/effect/IOLocalSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,16 @@ class IOLocalSpec extends BaseSpec {

io must completeAs(0)
}

"do not leak internal updates outside of a scope" in ticked { implicit ticker =>
val io = for {
local <- IOLocal(0)
inside <- local.scope(1).surround(local.getAndSet(2))
outside <- local.get
} yield (inside, outside)

io must completeAs((1, 0))
}
}

}