最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

RxJS根据发射值重复

运维笔记admin14浏览0评论

RxJS根据发射值重复

RxJS根据发射值重复

我试图根据repeat字段中返回的值来condition一个承诺调用。以下块不起作用,因为v未定义并随机抛出TypeError: Cannot read property 'condition' of undefined

console.log的o / p是{ Items: [ 1, 2, 3, 4, 5 ], condition: 5, time: 1513827310333 }

JSFiddle

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));
回答如下:

得到它使用外部标志,每次重复评估源。

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/ajax/libs/rxjs/5.5.5/Rx.min.js"></script>

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论