Skip to content

Instantly share code, notes, and snippets.

@khannurien
Last active July 2, 2021 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khannurien/93db1a2276e4bb70485c53b506304c17 to your computer and use it in GitHub Desktop.
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.
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