Skip to content

Instantly share code, notes, and snippets.

@vladimir-ivanov
Last active June 23, 2021 23:09
Show Gist options
  • Save vladimir-ivanov/c006c1757a6e263581d8d4dcf78ac324 to your computer and use it in GitHub Desktop.
Save vladimir-ivanov/c006c1757a6e263581d8d4dcf78ac324 to your computer and use it in GitHub Desktop.
rxjs reset scan stream and pause/ start
import { BehaviorSubject, Observable } from 'rxjs';
import {
combineLatest, filter, map, scan, tap,
} from 'rxjs/operators';
const scanResetPause = ($isBusy: Observable<boolean>) => {
return interval(2000).pipe(
scan((acc, value) => {
if (!isBusy$.getValue()) {
return { prevIsBusy: false, value };
}
if (!acc.prevIsBusy) {
return { prevIsBusy: true, value };
}
return { prevIsBusy: true, value: acc.value + value };
}, ({ prevIsBusy: false, value: 0 })),
combineLatest(isBusy$),
filter(([, isBusy]) => !isBusy),
map(([{ value }]) => value),
tap(c => console.warn(c, 'result')),
);
}
}
let busy = false;
const isBusy$ = new BehaviorSubject(busy);
setInterval(() => {
busy = !busy;
isBusy$.next(busy);
}, 5000);
scanResetPause(isBusy$).subscribe(console.warn);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment