RxJS race() Join Operator

The RxJS race() operator is a join operator that creates an output Observable, which shows the exact mirror copy of the first source observable.

In other words, we can say that the race() operator emits the first used operator as a result.

Syntax:

Following is the syntax of the race() operator:

race(observables: array[]): Observable

Parameter Explanation

observable: It specifies that the argument for this operator is an array of Observable.

Return value

The race() operator's return value is a single observable that will be an exact mirror copy of the first source observable.

Let us see some examples of race() operator to understand it clearly.

Example 1 (Simple example)

import { of, race } from 'rxjs'; import { concat } from 'rxjs/operators'; let list1 = of(1, 2, 3, 4, 5); let list2 = of(7, 9, 11, 17, 23) let final_val = race(list1, list2); final_val.subscribe(x => console.log(x));

Output:

After executing the above example, you will see the following result:

In the above example, you can see that the race() operator has displayed the exact same first list as result in the output.

Example 2 (Race with 4 observables)

import { mapTo } from 'rxjs/operators'; import { interval } from 'rxjs/observable/interval'; import { race } from 'rxjs/observable/race'; // It takes the first observable to emit const example = race( //emit every 1.5s interval(1500), //emit every 1s interval(1000).pipe(mapTo('1s won!')), //emit every 2s interval(2000), //emit every 2.5s interval(2500) const subscribe = example.subscribe(val => console.log(val));

Output:

After executing the above example, you will see the following result:

Example 3 (race with an error)

import { delay, map } from 'rxjs/operators'; import { of, race } from 'rxjs'; //It will throw an error and ignore the other observables. const first = of('first').pipe( delay(100), map(_ => { throw 'error'; const second = of('second').pipe(delay(200)); const third = of('third').pipe(delay(300)); race(first, second, third).subscribe(val => console.log(val));

Output:

After executing the above example, you will see the following result:

Here, you can see that it has thrown an error and does not entertain the other variables.

Next Topic RxJS Operators