Skip to content

Instantly share code, notes, and snippets.

@aeldar
Last active September 6, 2019 16:21
Show Gist options
  • Save aeldar/446b310e733bcfa0155e8cf7049c2214 to your computer and use it in GitHub Desktop.
Save aeldar/446b310e733bcfa0155e8cf7049c2214 to your computer and use it in GitHub Desktop.
RxJS operator to map emitted value to `true` and to emit `false` after some period of inactivity (On/AutoOff behavior)
import { merge, Observable, Subject } from 'rxjs';
import { debounceTime, map } from 'rxjs/operators';
// Emit `true` on any source emission, then emit `false` after period of inactivity
const turnOffAfter = (timeout: number) => (source: Observable<any>) => merge(
source.pipe(map(_ => true)), // map original value to `true`
source.pipe(debounceTime(timeout), map(_ => false)), // emit `false` after timeout
);
// Example usage
const trackStart: Subject<void> = new Subject<void>();
const onOff$: Observable<boolean> = trackStart.asObservable()
.pipe(
turnOffAfter(3_000),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment