Hyperlinkv0.8.0-beta.28

SubscriptionRef

SubscriptionRef.getAndUpdateSomeEffectconsteffect/SubscriptionRef.ts:417
<A, R, E>(update: (a: A) => Effect.Effect<Option.Option<A>, E, R>): (
  self: SubscriptionRef<A>
) => Effect.Effect<A, E, R>
<A, R, E>(
  self: SubscriptionRef<A>,
  update: (a: A) => Effect.Effect<Option.Option<A>, E, R>
): Effect.Effect<A, E, R>

Retrieves the current value and optionally updates the reference effectfully.

When to use

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

Details

If the effect succeeds with Option.some, the new value is set and published. If it succeeds with Option.none, the reference is left unchanged and no update is published.

Example (Getting and conditionally updating with an effect)

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

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

  const oldValue = yield* SubscriptionRef.getAndUpdateSomeEffect(
    ref,
    (n) => Effect.succeed(n > 5 ? Option.some(n + 3) : Option.none())
  )
  console.log("Old value:", oldValue)

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