Skip to content

Function: race()

race<T>(...streams): Stream<T[number]>

Defined in: streams/race.ts:20

Returns a stream that races multiple input streams. It emits values from the first stream that produces a value, then cancels all other streams.

This operator is useful for scenarios where you only need the result from the fastest of several asynchronous operations. For example, fetching data from multiple servers and only taking the result from the one that responds first.

Once the winning stream completes, the output stream also completes. If the winning stream emits an error, the output stream will emit that error.

Type Parameters

T

T extends readonly unknown[] = any[]

A tuple type representing the combined values from the streams.

Parameters

streams

...{ [K in string | number | symbol]: Stream<T[K<K>]> | Promise<T[K<K>]> | T[K<K>][] }

An array of streams to race against each other.

Returns

Stream<T[number]>

A new stream that emits values from the first stream to produce a value.

Examples

From race.spec.ts:4

typescript
const stream1 = createSubject<number>();
const stream2 = createSubject<number>();
const results: number[] = [];
const racedStream = race(stream1, stream2);
racedStream.subscribe({
  next: (value) => {
    results.push(value);
    if (results.length === 2) {
      expect(results).toEqual([1, 2]);
      done();
    }
  },
  error: done.fail,
  complete: done.fail,
});
stream1.next(1);
stream1.next(2);
stream2.next(3);

Released under the MIT License.