Andrey W
Andrey W

Reputation: 33

RXJS How to emit subscribtion only if another Observable is falsy

Need to emit subscription only if other observable is falsy. Sample code:

const loadingSubject$ = new BehaviorSubject<boolean>(false);
const valueSubject$ = new BehaviorSubject<string>('');

valueSubject$
  .pipe(
     // some conditions
  )
  .subscribe(
    value => {
      console.log(value);
    }
  );

valueSubject$.next('1') // '1'
valueSubject$.next('2') // '2'
loadingSubject$.next(true);
valueSubject$.next('3') // <nothing>
valueSubject$.next('4') // <nothing>
loadingSubject$.next(false);
valueSubject$.next('5') // '5'

More complicated case - not emit subscription also during some timeout after other observable is became falsy. Sample code for 100ms:

const loadingSubject$ = new BehaviorSubject<boolean>(false);
const valueSubject$ = new BehaviorSubject<string>('');

valueSubject$
  .pipe(
     // some conditions
  )
  .subscribe(
    value => {
      console.log(value);
    }
  );

valueSubject$.next('1') // '1'
valueSubject$.next('2') // '2'
loadingSubject$.next(true);
valueSubject$.next('3') // <nothing>
loadingSubject$.next(false);
valueSubject$.next('4') // <nothing>
setTimeout(() => {
  valueSubject$.next('5') // '5'
}, 101);

Upvotes: 0

Views: 440

Answers (1)

Andrei
Andrei

Reputation: 12036

valueSubject$
  .pipe(
    withLatestFrom(loadingSubject),
    filter(([_, loading]) => !loading),
    map(([v]) => v)
  )
  .subscribe(
    value => {
      console.log(value);
    }
  );

Upvotes: 1

Related Questions