Hyperlinkv0.8.0-beta.28

TxSubscriptionRef

TxSubscriptionRef.modifyconsteffect/TxSubscriptionRef.ts:192
<A, B>(f: (current: A) => [returnValue: B, newValue: A]): (
  self: TxSubscriptionRef<A>
) => Effect.Effect<B>
<A, B>(
  self: TxSubscriptionRef<A>,
  f: (current: A) => [returnValue: B, newValue: A]
): Effect.Effect<B>

Modifies the value of the TxSubscriptionRef using a function that returns both a result and the new value. The new value is published to all subscribers atomically.

When to use

Use to compute a separate return value and next TxSubscriptionRef state in one transactional update.

Example (Modifying and returning a value)

import { Effect, TxSubscriptionRef } from "effect"

const program = Effect.gen(function*() {
  const ref = yield* TxSubscriptionRef.make(10)
  const result = yield* TxSubscriptionRef.modify(ref, (n) => [`was ${n}`, n + 1])
  console.log(result) // "was 10"
  console.log(yield* TxSubscriptionRef.get(ref)) // 11
})
mutationsupdateset
export const modify: {
  <A, B>(
    f: (current: A) => [returnValue: B, newValue: A]
  ): (self: TxSubscriptionRef<A>) => Effect.Effect<B>
  <A, B>(
    self: TxSubscriptionRef<A>,
    f: (current: A) => [returnValue: B, newValue: A]
  ): Effect.Effect<B>
} = dual(
  2,
  <A, B>(
    self: TxSubscriptionRef<A>,
    f: (current: A) => [returnValue: B, newValue: A]
  ): Effect.Effect<B> =>
    Effect.gen(function*() {
      const current = yield* TxRef.get(self.ref)
      const [returnValue, newValue] = f(current)
      yield* TxRef.set(self.ref, newValue)
      yield* TxPubSub.publish(self.pubsub, newValue)
      return returnValue
    }).pipe(Effect.tx)
)
Referenced by 5 symbols