簡體   English   中英

如何使用 debounceTime 通過鍵獲取可觀察的最后一個值

[英]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

我需要使用哪個運算符來實現這一目標?

由於您對debounceTimesetInterval延遲使用相同的值,因此debounceTime時間跨度不會通過,也不會發出任何值。

現在,有兩種選擇:

  1. 降低debounceTime計時器,但它將導致僅調度最新值,因為 debounce 將忽略關閉發出的值
  2. 刪除debounceTime運算符並獲得所需的行為

我假設您想要排放之間的某種延遲,您可以使用bufferTime來收集一段時間內的不同值,然后使用mergeAll來展平收集到的值

employeeChanged
  .pipe(
    distinctUntilChanged(),
    bufferTime(1000),
    mergeAll()
  )
  .subscribe(key => {
    console.log(`Employee update: ${key}`);
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM