variable / @typed/fx/Fx

when

Conditionally emits one of two values based on the boolean value emitted by the condition stream.

Package version
2.0.0-beta.7
Category
Conditional sources
Since
1.0.0

Follow one execution

Conditionally emits one of two values based on the boolean value emitted by the condition stream.

Fx timelinewhen selects a value for each spaced conditionwhen
Operatorwhen(condition, { onTrue, onFalse })
Read this diagram

Follow each lane from left to right. Events stacked vertically share a tick; the green cursor marks the current time across every lane.

  • A value
    The text inside the pill is the emitted value.
  • Work starts
    The raised chevron starts an inner run (^ in the source).
  • The run returns
    The vertical bar ends this lane’s run.
  • A cause is delivered
    The exclamation mark belongs to this lane.
  • Work is interrupted
    The cross marks cancellation of this run.
  • Current time
    The line and diamond move together across all lanes.
  • Happening now
    A highlighted event is at the current tick.
  • Still ahead
    Muted, dashed values have not happened yet.
  • Time continues
    The lane’s arrow is not a return marker. An empty stretch can be quiet work that is still running.

Illustrated ticks start at 0. At 1×, one illustrated tick takes one second; captions specify real durations when timing matters. A cause or interruption belongs to its lane, and other work may continue. Scroll horizontally to inspect the rest of a long timeline.

It delegates branch switching to if; its constant branches acquire no resources. The Scope owns scheduled branch fibers, replacement awaits their interruption, and source completion waits for the latest selected branch.

Source implementation · Learn the surrounding model

Compare all Fx timelines →

Import

import { when } from "@typed/fx/Fx";

Signatures

export declare const when: <E, R, B, C>(condition: Fx<boolean, E, R>, matchers: {
    onTrue: B;
    onFalse: C;
}) => Fx<B | C, E, R | Scope>;

Why

when is the value-only form of if, implemented with switchMap. Each condition push selects a constant inner Fx, but a newer condition can interrupt that inner before it emits; output cardinality can therefore be lower than the number of condition values.

Ownership and lifetime

It delegates branch switching to if; its constant branches acquire no resources. The Scope owns scheduled branch fibers, replacement awaits their interruption, and source completion waits for the latest selected branch.

Examples

import { Fx } from "@typed/fx"
const program = Fx.collectAll(
  Fx.when(Fx.fromIterable([true, false]), { onTrue: "yes", onFalse: "no" })
) // the later `false` may replace `true` before "yes" is emitted

Other public imports

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

Source