function / @typed/fx/Sink

withStateSemaphore

Runs a callback with private state whose effectful reads and writes are serialized.

Package version
2.0.0-beta.7
Category
Stateful delivery
Since
1.0.0

Import

import { withStateSemaphore } from "@typed/fx/Sink";

Signatures

export declare function withStateSemaphore<A, E, R, B, R2>(sink: Sink<A, E, R>, state: B, f: (sink: Sink.WithStateSemaphore<A, E, R, B>, params: {
    signal: AbortSignal;
    scheduler: Scheduler;
}) => Effect.Effect<unknown, never, R2>): Effect.Effect<void, never, R | R2>;

Why

Overlapping asynchronous callbacks need a lock to prevent multiple updates from reading the same prior state.

Ownership and lifetime

Each execution owns one mutable cell and one single-permit semaphore. Modify Effects serialize in semaphore-acquisition order, release the permit on completion or interruption, and expose their typed errors and services. Constructing an Effect does not acquire the permit; running it does. Exit aborts the surrounding callback fiber.

Examples

import { Effect } from "effect"
import * as Sink from "@typed/fx/Sink"
const base = Sink.make(Effect.logError, Effect.log)
const program = Sink.withStateSemaphore(base, 0, (state) =>
  state.updateEffect((n) => Effect.succeed(n + 1)).pipe(Effect.andThen(state.earlyExit)))

Other public imports

These import paths expose the same declaration. Each page retains its own public name and signature.

Source