Hyperlinkv0.8.0-beta.28

Ref

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

Updates the value of the Ref atomically using the given function and returns the new value.

When to use

Use to apply a Ref state transition and return the new stored value.

Example (Updating and returning the new value)

import { Effect, Ref } from "effect"

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

  // Update and get the new value in one operation
  const newValue = yield* Ref.updateAndGet(counter, (n) => n * 3)
  console.log(newValue) // 15

  // Verify the ref contains the new value
  const current = yield* Ref.get(counter)
  console.log(current) // 15
})
Source effect/Ref.ts:6514 lines
export const updateAndGet = 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(() => self.ref.current = f(self.ref.current)))
Referenced by 1 symbols