gpt4 book ai didi

angular - 如何在 OnDestroy 中完成事件的 debounceTime

转载 作者:行者123 更新时间:2023-12-04 10:01:08 24 4
gpt4 key购买 nike

当用户更改输入字段时,我当前正在保存值。我不想在每次输入新字符时都保存该值,因此我使用 rxjs debounceTime 在 3000 毫秒(只是一个示例)没有更改后进行保存。

this.subscription.add(this.form.controls.inputControl.valueChanges
.pipe(debounceTime(3000))
.subscribe(value => {
// execute HTTP call with value
}));

ngOnDestroy(): void {
this.subscription.unsubscribe();
}

如果用户更改该值并且 OnDestroy 在达到 3000 毫秒计时器之前被调用,则不会再执行该调用。我想知道是否有办法在销毁组件之前取消事件计时器并执行所有剩余的可观察对象。

编辑:另一个选项可能是用户在有未保存的更改时收到警告。就像谷歌日历在添加新任务和离开页面时所做的那样

最佳答案

const destroyed = new Subject();
const isTimerActive = new BehaviorSubject(false);

const stop$ = combineLatest(destroyed, isTimerActive)
.pipe(
filter(([isDestroyed, isTimerActive]) => isDestroyed && !isTimerActive)
);

src$.pipe(
debounce(
() => (
// Now if the component is destroyed, it will not unsubscribe from this stream
isTimerActive.next(true),
timer(/* ... */)
)
),
switchMap(v => makeRequest(v)),

// If the component is destroyed, then after sending this
// the stream will be unsubscribed
tap(() => isTimerActive.next(false)),

takeUntil(stop$)
).subscribe(/* ... */)


ngOnDestroy () {
this.destroyed.next(true);
this.destroyed.complete();
}

重要的是要注意,只有当我们完成所有涉及延迟后发出的值的任务时,计时器才被声明为非事件( isTimerActive.next(false))。

这是因为如果 destroyedtrue我们立即做 isTimerActive.next(false) ,取消订阅会发生 同步 ,这意味着您将无法使用该值执行任何其他操作。

关于angular - 如何在 OnDestroy 中完成事件的 debounceTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61813792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com