Hyperlinkv0.8.0-beta.28

SubscriptionRef

SubscriptionRef.getAndUpdateSomeconsteffect/SubscriptionRef.ts:364
<A>(update: (a: A) => Option.Option<A>): (
  self: SubscriptionRef<A>
) => Effect.Effect<A>
<A>(
  self: SubscriptionRef<A>,
  update: (a: A) => Option.Option<A>
): Effect.Effect<A>

Retrieves the current value and optionally updates the reference.

When to use

Use to read the old SubscriptionRef value while applying a synchronous update only when a new value is available.

Details

If the function returns Option.some, the new value is set and published. If it returns Option.none, the reference is left unchanged and no update is published.

Example (Getting and conditionally updating a value)

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

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

  const oldValue = yield* SubscriptionRef.getAndUpdateSome(
    ref,
    (n) => n > 5 ? Option.some(n * 2) : Option.none()
  )
  console.log("Old value:", oldValue)

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