race
race
is used to select an observable sequences that is the first to produce values. As soon as one of the sequences starts emitting values the other sequences are unsubscribed and completely ignored.
The resulting stream completes when the selected input stream completes and will throw an error if this one stream errors out. It will also never complete if this inner stream doesn’t complete.
The operator works in the following way:
In the diagram below you can see the race operator combining two streams
A
and
B
each producing 3 items but only the values from the stream
A
are emitted since this stream starts emitting values first.
Usage
Link to this section
This operator can be useful if you have multiple resources that can provide values, for example, servers around the world, but due to network conditions the latency is not predictable and varies significantly. Using this operator you can send the same request out to multiple data sources and consume the result of the first that responds.
Here’s an example of using
race
to run multiple HTTP requests and cancel one of them:
<>Copyconst a = fromFetch('https://api.mocki.io/v1/0350b5d5'); const b = fromFetch('https://api.mocki.io/v1/ce5f60e2'); race(a, b).subscribe((response) => console.log(response));
Playground
Link to this sectionAdditional resources
Link to this sectionOfficial documentation See also
Link to this section