Last active
September 6, 2019 16:21
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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