RxJS distinct

2020-10-14 10:06 更新

返回一個 Observable,它發(fā)出源 Observable 發(fā)出的所有項目,這些項目與以前的項目相比是不同的。

distinct<T, K>(keySelector?: (value: T) => K, flushes?: Observable<any>):MonoTypeOperatorFunction<T>

參量

keySelector 可選的。 默認值為 undefined。 可選功能,用于選擇您要檢查為不同的值。
flushes 可選的。 默認值為 undefined。         可選 Observable,用于刷新運算符的內部HashSet。

returns

MonoTypeOperatorFunction<T>:一個 Observable,它從源 Observable 發(fā)出具有不同值的項目。

描述

如果提供了 keySelector 函數,則它將可觀察到的源中的每個值投影到一個新值中 檢查與先前預測的值是否相等。 如果未提供 keySelector 函數,它將使用來自 可以直接通過對先前值的相等性檢查來觀察源。

在支持的 JavaScript 運行時中 Set,此運算符將使用 Set來提高非重復值檢查的性能。

在其他運行時,該運營商將使用一個最小的實現 Set依賴于一個 ArrayindexOf下 引擎蓋,因此當檢查更多的值以區(qū)別時,性能將下降。 即使在較新的瀏覽器中,長期運行 distinct 使用可能會導致內存泄漏。 為了在某些情況下緩解這種情況, 一個可選 flushes還提供了 參數,以便 內部 Set可以被“清除”,基本上清除了其價值。

例子

一個簡單的數字例子

import { of } from 'rxjs';
import { distinct } from 'rxjs/operators';


of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1).pipe(
    distinct(),
  )
  .subscribe(x => console.log(x)); // 1, 2, 3, 4

使用 keySelector 函數的示例

import { of } from 'rxjs';
import { distinct } from 'rxjs/operators';


interface Person {
   age: number,
   name: string
}


of<Person>(
    { age: 4, name: 'Foo'},
    { age: 7, name: 'Bar'},
    { age: 5, name: 'Foo'},
  ).pipe(
    distinct((p: Person) => p.name),
  )
  .subscribe(x => console.log(x));


// displays:
// { age: 4, name: 'Foo' }
// { age: 7, name: 'Bar' }

也可以看看

以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號