@bemedev/rx-add-ons
Version:
A collection of RxJS operators and utilities to enhance reactive programming capabilities.
42 lines (38 loc) • 1.62 kB
JavaScript
;
var Subject = require('rxjs/internal/Subject');
var empty = require('rxjs/internal/observable/empty');
var scan = require('rxjs/internal/operators/scan');
var startWith = require('rxjs/internal/operators/startWith');
var switchMap = require('rxjs/internal/operators/switchMap');
const createPausable = (source$, observer) => {
// Control Subject for start, stop, pause, and resume
const control$ = new Subject.Subject();
// State management for the observable
const controlled$ = control$.pipe(startWith.startWith('stop'), // Start in "stopped" state
scan.scan((state, action) => {
if (action === 'start' && state !== 'running')
return 'running';
if (action === 'stop')
return 'stopped';
if (action === 'pause' && state === 'running')
return 'paused';
if (action === 'resume' && state === 'paused')
return 'running';
return state; // Ignore invalid transitions
}, 'stopped'), switchMap.switchMap(state => {
if (state === 'running')
return source$; // Emit values when running
return empty.EMPTY; // Emit nothing when paused or stopped
}));
// Subscribe to the controlled Observable
controlled$.subscribe(observer);
return {
start: () => control$.next('start'),
stop: () => control$.next('stop'),
pause: () => control$.next('pause'),
resume: () => control$.next('resume'),
command: (action) => control$.next(action),
};
};
exports.createPausable = createPausable;
//# sourceMappingURL=pausable.cjs.map