[英]How to get last value of observable by key using debounceTime
employeeChanged: Subject<any> = new Subject<any>();
setInterval(() => {
this.employeeChanged.next(1);
this.employeeChanged.next(1);
this.employeeChanged.next(2);
this.employeeChanged.next(2);
this.employeeChanged.next(3);
this.employeeChanged.next(3);
},1000);
this.employeeChanged.pipe(debounceTime(1000),distinctUntilChanged()).subscribe(((key) => {
console.log(`Employee update: ${key}`);
}));
我的例子看起來像這樣。 我想通過我提供給主題 observable 的鍵來獲取最新值,所以我的輸出看起來像這樣
Employee update: 1
Employee update: 2
Employee update: 3
我需要使用哪個運算符來實現這一目標?
由於您對debounceTime
和setInterval
延遲使用相同的值,因此debounceTime
時間跨度不會通過,也不會發出任何值。
現在,有兩種選擇:
debounceTime
計時器,但它將導致僅調度最新值,因為 debounce 將忽略關閉發出的值debounceTime
運算符並獲得所需的行為我假設您想要排放之間的某種延遲,您可以使用bufferTime
來收集一段時間內的不同值,然后使用mergeAll
來展平收集到的值
employeeChanged
.pipe(
distinctUntilChanged(),
bufferTime(1000),
mergeAll()
)
.subscribe(key => {
console.log(`Employee update: ${key}`);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.