Is there a RxJS operator that can replace set/clearTimeout in this specific case:
this.mouseEnterSubscription = this.mouseEnterStream
.subscribe(() => {
this.timeout = setTimeout(() => {
void this.playVideo();
}, 500)
});
this.mouseLeaveSubscription = this.mouseLeaveStream.subscribe(() => {
this.pauseVideo();
clearTimeout(this.timeout);
});
3
You can use debounceTime
to delay emitting until the indicated time has passed without receiving a new emission and you can use takeUntil
to complete an observable when another observable emits a value:
const mouseEnterSubscription = mouseEnterStream.pipe(
debounceTime(500),
takeUntil(mouseLeaveStream),
repeat(),
).subscribe(
() => playVideo()
);
With this code we wait 500ms before emitting, but will bail out if the mouseLeaveStream emits first. Because of the takeUntil
your mouseLeaveSubscription doesn’t need to worry about doing any cleanup work. We use repeat
to “restart” the completed source (otherwise it would only emit once).
const mouseLeaveSubscription = mouseLeaveStream.subscribe(
() => pauseVideo()
);
Here is a StackBlitz example.
0