Hyperlinkv0.8.0-beta.28

Ref

Ref.getAndUpdateconsteffect/Ref.ts:323
<A>(f: (a: A) => A): (self: Ref<A>) => Effect.Effect<A>
<A>(self: Ref<A>, f: (a: A) => A): Effect.Effect<A>

Gets the current value of the Ref, updates it with the given function, and returns the previous value atomically.

When to use

Use to derive a new Ref value while returning the previous value.

Example (Updating and returning the previous value)

import { Effect, Ref } from "effect"

const program = Effect.gen(function*() {
  const counter = yield* Ref.make(10)

  // Get current value and update it atomically
  const previous = yield* Ref.getAndUpdate(counter, (n) => n * 2)
  console.log(previous) // 10

  const current = yield* Ref.get(counter)
  console.log(current) // 20
})
Source effect/Ref.ts:3239 lines
export const getAndUpdate = dual<
  <A>(f: (a: A) => A) => (self: Ref<A>) => Effect.Effect<A>,
  <A>(self: Ref<A>, f: (a: A) => A) => Effect.Effect<A>
>(2, <A>(self: Ref<A>, f: (a: A) => A) =>
  Effect.sync(() => {
    const current = self.ref.current
    self.ref.current = f(current)
    return current
  }))
Referenced by 1 symbols