cats-effect icon indicating copy to clipboard operation
cats-effect copied to clipboard

Add scope to IOLocal

Open wunderk1nd-e opened this issue 2 years ago • 3 comments

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

wunderk1nd-e avatar Aug 17 '22 16:08 wunderk1nd-e

I think the CI failure might be an unrelated issue (flakiness?)

wunderk1nd-e avatar Aug 23 '22 09:08 wunderk1nd-e

Could be nice to have this as an instance method on IOLocal?

bplommer avatar Aug 23 '22 09:08 bplommer

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(_ => ???)

iRevive avatar Aug 26 '22 14:08 iRevive