race

signature: race(): Observable

The observable to emit first is used.

race - 图1

Examples

Example 1: race with 4 observables

( StackBlitz |
jsBin |
jsFiddle )

  1. import { mapTo } from 'rxjs/operators';
  2. import { interval } from 'rxjs/observable/interval';
  3. import { race } from 'rxjs/observable/race';
  4. //take the first observable to emit
  5. const example = race(
  6. //emit every 1.5s
  7. interval(1500),
  8. //emit every 1s
  9. interval(1000).pipe(mapTo('1s won!')),
  10. //emit every 2s
  11. interval(2000),
  12. //emit every 2.5s
  13. interval(2500)
  14. );
  15. //output: "1s won!"..."1s won!"...etc
  16. const subscribe = example.subscribe(val => console.log(val));
Example 2: race with an error

( StackBlitz |
jsFiddle )

  1. import { delay, map } from 'rxjs/operators';
  2. import { of } from 'rxjs/observable/of';
  3. import { race } from 'rxjs/observable/race';
  4. //Throws an error and ignores the other observables.
  5. const first = of('first').pipe(
  6. delay(100),
  7. map(_ => {
  8. throw 'error';
  9. })
  10. );
  11. const second = of('second').pipe(delay(200));
  12. const third = of('third').pipe(delay(300));
  13. race(first, second, third).subscribe(val => console.log(val));

Additional Resources

  • race
    :newspaper: - Official docs

:file_folder: Source Code:
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/race.ts