3 回答

TA貢獻(xiàn)1853條經(jīng)驗 獲得超6個贊
您可以debounceTime使用switchMap和進(jìn)行模擬delay。然后取消內(nèi)部 ObservabletakeUntil以防止發(fā)出等待值。
private updateSubject = new Subject<string>();
private interrupt = new Subject();
ngOnInit() {
this.updateSubject.pipe(
switchMap(val => of(val).pipe(
delay(3000),
takeUntil(this.interrupt)
))
).subscribe(val => publish(val));
}
doChange(val: string) {
this.updateSubject.next(val);
}
doImmediateChange(val: string) {
this.interrupt.next();
publish(val);
}
https://stackblitz.com/edit/rxjs-ya93fb

TA貢獻(xiàn)1820條經(jīng)驗 獲得超10個贊
使用競賽運算符:
第一個完成的observable成為唯一訂閱的observable,因此這個遞歸函數(shù)將在一次發(fā)射后完成take(1),然后重新訂閱() => this.raceRecursive()。
private timed$ = new Subject<string>();
private event$ = new Subject<string>();
ngOnInit() {
this.raceRecursive()
}
raceRecursive() {
race(
this.timed$.pipe(debounceTime(1000)),
this.event$
)
.pipe(take(1)) // force it to complete
.subscribe(
val => console.log(val), // srv call here
err => console.error(err),
() => this.raceRecursive() // reset it once complete
)
}
doChange(val: string) {
this.timed$.next(val)
}
doImmediateChange(val: string) {
this.event$.next(val)
}

TA貢獻(xiàn)1842條經(jīng)驗 獲得超21個贊
您可以使用debounce和race實現(xiàn)此行為:
使用您提供的代碼
private destroy$ = new Subject<void>();
private immediate$ = new Subject<void>();
private updateSubject$ = new Subject<string>();
constructor(private srv: PubSubService) {}
ngOnInit() {
this.updateSubject$.pipe(
takeUntil(this.destroy$),
debounce(() => race(timer(3000), this.immediate$))
).subscribe(val => {
this.srv.publishChange(val);
});
}
doChange(val: string, immediate?: boolean) {
this.updateSubject$.next(val);
if (immediate) this.immediate$.next();
}
// don't forget to unsubscribe
ngOnDestroy() {
this.destroy$.next();
}
立即發(fā)出更改將替換之前的正常更改(即去抖 3 秒),而不會延遲(感謝我們的種族可觀察)。
添加回答
舉報