使用distinctUntilChanged運營商。 (docs)
假設該對象的結構是:
{
articleId: 0,
comments: [ 'lorem', 'ipsum' ]
}
我們希望成爲酷派爲火力的傢伙,所以當更新的對象有不同的陣列,我們將更新實時評論。
我使用RxJS5
作爲觀測值,lodash
比較數組,因爲操作符的默認行爲不會以我們希望比較它們的方式進行比較。
// Our BehaviorSubject which emits new object.
// For those who don't know: it'll emit the latest emitted value when subscribing to it.
const object$ = new Rx.BehaviorSubject({
articleId: 0,
comments: [],
});
// If you want specific parts of your application
// to react only when a specific part of the object has changed, you
// have to create another observable using 'map' and
// 'distinctUntilChanged' operator and subscribe to it.
const comments$ = object$
.map(object => object.comments) // we want to emit comments only
.distinctUntilChanged((a, b) => _.isEqual(a, b)); // emit only when currently emitted value is different than previous one.
comments$.subscribe(v => console.log(v)); // log fresh comments
object$.next({
articleId: 1,
comments: [],
});
object$.next({
articleId: 1,
comments: ['lorem', 'ipsum'],
});
object$.next({
articleId: 2,
comments: ['lorem', 'ipsum'],
});
object$.next({
articleId: 2,
comments: ['lorem', 'ipsum', 'dolor', 'sit', 'amet'],
});
效果:
[]
["lorem", "ipsum"]
["lorem", "ipsum", "dolor", "sit", "amet"]
效果,而distinctUntilChanged
操作:
[]
[]
["lorem", "ipsum"]
["lorem", "ipsum"]
["lorem", "ipsum", "dolor", "sit", "amet"]
JSFiddle
我想你不希望在你的應用程序中使用終極版? –
是的,希望。我已經在客戶端運行了REDX(Angular),並且在服務器端我只是希望有一些Rxjs主題來處理它,如果可能的話。 –
像ngrx ['select'](https://github.com/ngrx/core/blob/v1.2.0/src/operator/select.ts)操作符聽起來適合您的用例。 – cartant