Skip to content

Function: fork()

fork<T, R>(options): Operator<T, R>

Defined in: operators/fork.ts:59

Creates a stream operator that routes each source value through a specific handler based on matching predicates defined in the provided ForkOptions.

For each value from the source stream:

  1. Iterates over the options array.
  2. Executes the on predicate for each option until one returns true.
  3. Calls the corresponding handler for the first matching option.
  4. Flattens the result (stream, value, promise, or array) sequentially into the output stream.

If no predicate matches a value, an error is thrown.

This operator allows conditional branching in streams based on the content of each item.

Type Parameters

T

T = any

The type of values in the source stream.

R

R = any

The type of values emitted by the output stream.

Parameters

options

ForkOption<T, R>[]

Array of ForkOption objects defining predicates and handlers.

Returns

Operator<T, R>

An Operator instance suitable for use in a stream's pipe method.

Throws

If a source value does not match any predicate.

Examples

From fork.spec.ts:16

typescript
let options: Array<{ on: (value: number) => boolean; handler: any }> = [
  { on: (value: number) => value <= 5, handler: () => of('Small number') },
  {
    on: (value: number) => value > 5 && value <= 15,
    handler: () => of('Medium number'),
  },
  { on: (value: number) => value > 15, handler: () => of('Large number') },
];

const result: string[] = [];
source$ = from([1, 5, 10, 20]).pipe(fork(options));
source$.subscribe({
  next: (value: any) => result.push(value),
  complete: () => {
    expect(result).toEqual([
      'Small number',
      'Small number',
      'Medium number',
      'Large number',
    ]);
    done();
  },
});

Released under the MIT License.