Learn RxJS
Search…
race

signature: race(): Observable

The observable to emit first is used.

Examples

Example 1: race with 4 observables
1
// RxJS v6+
2
import { mapTo } from 'rxjs/operators';
3
import { interval } from 'rxjs/observable/interval';
4
import { race } from 'rxjs/observable/race';
5
6
//take the first observable to emit
7
const example = race(
8
//emit every 1.5s
9
interval(1500),
10
//emit every 1s
11
interval(1000).pipe(mapTo('1s won!')),
12
//emit every 2s
13
interval(2000),
14
//emit every 2.5s
15
interval(2500)
16
);
17
//output: "1s won!"..."1s won!"...etc
18
const subscribe = example.subscribe(val => console.log(val));
Copied!
Example 2: race with an error
1
// RxJS v6+
2
import { delay, map } from 'rxjs/operators';
3
import { of, race } from 'rxjs';
4
5
//Throws an error and ignores the other observables.
6
const first = of('first').pipe(
7
delay(100),
8
map(_ => {
9
throw 'error';
10
})
11
);
12
const second = of('second').pipe(delay(200));
13
const third = of('third').pipe(delay(300));
14
// nothing logged
15
race(first, second, third).subscribe(val => console.log(val));
Copied!

Additional Resources

  • race 📰 - Official docs
  • race - In Depth Dev Reference
Last modified 1yr ago