race

function stable

Returns an observable that mirrors the first source observable to emit an item.

race<T>(...sources: (Observable<T> | InteropObservable<T> | AsyncIterable<T> | PromiseLike<T> | ArrayLike<T> | Iterable<...> | ReadableStreamLike<...> | ObservableInput<...>[])[]): Observable<any>

Parameters

sources

Type: (Observable | InteropObservable | AsyncIterable | PromiseLike | ArrayLike | Iterable<...> | ReadableStreamLike<...> | ObservableInput<...>[])[].

Returns

Observable<any>: an Observable that mirrors the output of the first Observable to emit an item.

Description

race marble diagram

race returns an observable, that when subscribed to, subscribes to all source observables immediately. As soon as one of the source observables emits a value, the result unsubscribes from the other sources. The resulting observable will forward all notifications, including error and completion, from the "winning" source observable.

If one of the used source observable throws an errors before a first notification the race operator will also throw an error, no matter if another source observable could potentially win the race.

race can be useful for selecting the response from the fastest network connection for HTTP or WebSockets. race can also be useful for switching observable context based on user input.

Example

Subscribes to the observable that was the first to start emitting.

import { race, interval } from 'rxjs';
import { mapTo } from 'rxjs/operators';

const obs1 = interval(1000).pipe(mapTo('fast one'));
const obs2 = interval(3000).pipe(mapTo('medium one'));
const obs3 = interval(5000).pipe(mapTo('slow one'));

race(obs3, obs1, obs2)
.subscribe(
  winner => console.log(winner)
);

// Outputs
// a series of 'fast one'

© 2015–2021 Google, Inc., Netflix, Inc., Microsoft Corp. and contributors.
Code licensed under an Apache-2.0 License. Documentation licensed under CC BY 4.0.
https://rxjs.dev/api/index/function/race