本文介绍了RxJS 根据发出的值重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试根据 condition
字段中返回的值repeat
一个承诺调用.以下块不起作用,因为 v
未定义并随机抛出 TypeError: Cannot read property 'condition' of undefined
I am trying to repeat
a promise call depending on the value returned in condition
field. The following block doesn't work because v
is undefined and randomly throws TypeError: Cannot read property 'condition' of undefined
console.log 的 o/p 是 { Items: [ 1, 2, 3, 4, 5 ], condition: 5, time: 1513827310333 }
the o/p of console.log is { Items: [ 1, 2, 3, 4, 5 ], condition: 5, time: 1513827310333 }
const source = Rx.Observable.fromPromise(
Promise.resolve({
Items: [1, 2, 3, 4, 5],
condition: Math.floor(Math.random() * 10),
time: +new Date()
})
);
source
.map(val => val)
.repeatWhen(val => {
return val.map(v => { // v is undefined
if (v.condition > 0) {
return Rx.Observable.of(v);
} else {
return Rx.Observable.empty();
}
});
})
.finally(() => {
done();
})
.subscribe(val => console.log(val));
推荐答案
让它与外部标志一起工作,并且每次重复都会评估源.
Got it working with an external flag an the source is evaluated for every repetition.
const source = Rx.Observable.defer(() =>
Promise.resolve({
Items: [1, 2, 3, 4, 5],
condition: Math.floor(Math.random() * 10),
time: +new Date()
})
);
let condition = false;
source
.repeatWhen(notifications => {
return notifications
.scan(() => {
return condition;
}, false)
.delay(100)
.takeWhile(() => {
return condition;
});
})
.do(x => (condition = x.condition !== 0))
.finally(console.log("done"))
.subscribe(console.log);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.5/Rx.min.js"></script>
这篇关于RxJS 根据发出的值重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!