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
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.