cats-effect
cats-effect copied to clipboard
Add scope to IOLocal
Thought it could be useful to have a way to update the value of an IOLocal within the scope of some task IO[A]
Motivation was being able to set log context here: https://github.com/typelevel/log4cats/pull/676
I think the CI failure might be an unrelated issue (flakiness?)
Could be nice to have this as an instance method on IOLocal?
What if we use Resource instead? From my point of view, it offers better flexibility and composability
trait IOLocal[A] {
def scope[A](value: A): Resource[IO, A] =
Resource.make(local.getAndSet(value))(local.set)
}
That way, the scope can be managed for Resource, fs2.Stream, and IO:
val local: IOLocal[String] = ???
val stream: fs2.Stream[IO, ...] = fs2.Stream.resource(local.scope("my-scope")).evalMap(_ => ???)
val resource: Resource[IO, ...] = local.scope("external").flatMap(_ => ??? >> local.scope("internal"))
val io: IO[...] = local.scope("my-scope").use(_ => ???)