function / @typed/fx

Sink.withState

Runs a callback with an early-exit sink and a private Effect Ref initialized to state.

Package version
2.0.0-beta.13
Category
Stateful delivery
Since
1.0.0
Member of
Sink

Import

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

Access Sink.withState through the imported Sink export. Its declaration below describes the member.

This public exposure is a re-export. Its import path is supported; declaration documentation is shared with the other public exposures below.

Signatures

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

Why

It supports stateful consumer protocols while keeping their state local to one run.

Ownership and lifetime

Each execution creates one Ref and owns it until exit or interruption. Ref operations are lazy atomic Effects: serialized callback execution preserves producer order, while concurrent execution is ordered by scheduling. No state is shared across withState executions.

Examples

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

Other public imports

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

Source