Last active
July 2, 2021 07:04
-
-
Save khannurien/93db1a2276e4bb70485c53b506304c17 to your computer and use it in GitHub Desktop.
Using rxjs operators, conditionally combine results from two Observables based on a predicate regarding values from the first Observable.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { iif, of } from "rxjs"; | |
import { map, switchMap, withLatestFrom } from 'rxjs/operators'; | |
const values1 = [1, 2, 3, 4]; | |
const values2 = [5, 6, 7]; | |
const values1$ = of(values1); | |
const values2$ = of(values2); | |
values1$.pipe( | |
switchMap((result1) => | |
iif( | |
() => result1[0] === 1, | |
values1$.pipe( | |
withLatestFrom(values2$), | |
map( | |
([first, second]: [number[], number[]]) => [...first, ...second] | |
) | |
), | |
values1$ | |
) | |
) | |
).subscribe(console.log); | |
// [ 1, 2, 3, 4, 5, 6, 7 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment