我正在使用combineLatest observable和两个流和选择器函数。
const todos = Rx.Observable.of([{
id: 1,
completed: false,
text: 'one'
}, {
id: 1,
completed: true,
text: 'two'
}]);
const filter = Rx.Observable.of('SHOW_ALL');
const getTodos = Rx.Observable.combineLatest(todos, filter, (todos, filter) => {
console.log('calculation');
// doing some calculation...
return todos;
});
getTodos.subscribe(console.log)
getTodos.subscribe(console.log)
<script src="https://unpkg.com/@reactivex/rxjs@5.0.3/dist/global/Rx.js"></script>
我需要结果选择器只为订阅者运行一次以避免重新计算。例如,缓存结果,如果两个输入都没有变化,则给我最新的值。
有一种方法可以用RxJS做到这一点吗?
答案 0 :(得分:2)
我认为您正在寻找shareReplay
运营商。它允许您在所有订阅者之间共享combineLatest
生成的值。
https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/sharereplay.md
如果您不想在订阅者从0到1或更多时自动连接/断开连接,您可能需要查看replay
,反之亦然。
https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/replay.md
const getTodos = Rx.Observable.combineLatest(todos, filter, (todos, filter) => {
console.log('calculation');
// doing some calculation...
return todos;
})
.shareReplay();
这是一个正在运行的例子:
const todos = Rx.Observable.of([{
id: 1,
completed: false,
text: 'one'
}, {
id: 1,
completed: true,
text: 'two'
}]);
const filter = Rx.Observable.of('SHOW_ALL');
const getTodos = Rx.Observable.combineLatest(todos, filter, (todos, filter) => {
console.log('calculation');
// doing some calculation...
return todos;
})
.shareReplay();
getTodos.subscribe(console.log.bind(console))
getTodos.subscribe(console.log.bind(console))
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.lite.js"></script>
&#13;