Hyperlinkv0.8.0-beta.28

Ref

Ref.updateSomeconsteffect/Ref.ts:703
<A>(f: (a: A) => Option.Option<A>): (self: Ref<A>) => Effect.Effect<void>
<A>(self: Ref<A>, f: (a: A) => Option.Option<A>): Effect.Effect<void>

Updates the value of the Ref atomically using the given partial function.

When to use

Use to apply a conditional Ref update without returning a value.

Details

If the partial function returns Option.some, the Ref is updated with the new value. If it returns Option.none, the Ref is left unchanged.

Example (Conditionally updating a value)

import { Effect, Option, Ref } from "effect"

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

  // Only update if value is even
  yield* Ref.updateSome(
    counter,
    (n) => n % 2 === 0 ? Option.some(n * 2) : Option.none()
  )

  let current = yield* Ref.get(counter)
  console.log(current) // 5 (unchanged because 5 is odd)

  // Set to even number and try again
  yield* Ref.set(counter, 6)
  yield* Ref.updateSome(
    counter,
    (n) => n % 2 === 0 ? Option.some(n * 2) : Option.none()
  )

  current = yield* Ref.get(counter)
  console.log(current) // 12 (updated because 6 is even)
})
Source effect/Ref.ts:70310 lines
export const updateSome = dual<
  <A>(f: (a: A) => Option.Option<A>) => (self: Ref<A>) => Effect.Effect<void>,
  <A>(self: Ref<A>, f: (a: A) => Option.Option<A>) => Effect.Effect<void>
>(2, <A>(self: Ref<A>, f: (a: A) => Option.Option<A>) =>
  Effect.sync(() => {
    const option = f(self.ref.current)
    if (option._tag === "Some") {
      self.ref.current = option.value
    }
  }))
Referenced by 1 symbols