我正在尝试repeat
一个承诺调用,具体取决于condition
字段中返回的值。以下块无效,因为v
未定义且随机抛出TypeError: Cannot read property 'condition' of undefined
console.log的o / p为{ 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));
答案 0 :(得分:0)
使用外部标记,每次重复都会评估源。
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>
&#13;