user12207064
user12207064

Reputation:

logical OR combine 2 or more observable streams

I have 2 observables that both indicate if they're loading data or not. They come from @ngrx/data.

loadingA$: Observable<boolean>
loadingB$: Observable<boolean>

I'd like to "logical OR" combine the two to do whatever when either is true, using rxjs or more elegant method. Maybe ramdajs?, maybe a combined loading state? However different components need different combinations of loading streams.

Also, what if I have 20 streams, it shouldn't be limited to 2 streams only.

(!) I do not want to assign additional local variables.

Upvotes: 3

Views: 709

Answers (1)

Adrian Brand
Adrian Brand

Reputation: 21638

combineLatest(loadingA$, loadingB$).pipe(map((a, b) => a || b));

or

const anyLoading = (...observables: Observable<boolean>[]) => combineLatest(observables).pipe(
  map(bools => bools.some(loading => loading))
);

and use it

anyLoading(loadingA$, loadingB$);

const { combineLatest, BehaviorSubject } = rxjs;
const { map } = rxjs.operators;

const anyLoading = (...observables) => combineLatest(observables).pipe(
  map(bools => bools.some(loading => loading))
);

const loadingA$ = new BehaviorSubject(false);
const loadingB$ = new BehaviorSubject(true);

anyLoading(loadingA$, loadingB$).subscribe(loading => { console.log(loading); });

loadingB$.next(false);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.min.js"></script>

Upvotes: 1

Related Questions