Hyperlinkv0.8.0-beta.28

SubscriptionRef

SubscriptionRef.getAndUpdateconsteffect/SubscriptionRef.ts:276
<A>(update: (a: A) => A): (self: SubscriptionRef<A>) => Effect.Effect<A>
<A>(self: SubscriptionRef<A>, update: (a: A) => A): Effect.Effect<A>

Retrieves the current value and updates it atomically with the result of applying a function, notifying subscribers of the change.

Example (Getting and updating a value)

import { Effect, SubscriptionRef } from "effect"

const program = Effect.gen(function*() {
  const ref = yield* SubscriptionRef.make(10)

  const oldValue = yield* SubscriptionRef.getAndUpdate(ref, (n) => n * 2)
  console.log("Old value:", oldValue)

  const newValue = yield* SubscriptionRef.get(ref)
  console.log("New value:", newValue)
})
getters
export const getAndUpdate: {
  <A>(update: (a: A) => A): (self: SubscriptionRef<A>) => Effect.Effect<A>
  <A>(self: SubscriptionRef<A>, update: (a: A) => A): Effect.Effect<A>
} = dual(2, <A>(self: SubscriptionRef<A>, update: (a: A) => A) =>
  self.semaphore.withPermit(Effect.sync(() => {
    const current = self.value
    const newValue = update(current)
    setUnsafe(self, newValue)
    return current
  })))