【问题标题】:RxJS and Unreachable ElementsRxJS 和不可访问的元素
【发布时间】:2014-05-21 20:55:40
【问题描述】:

我有一个场景,给定一个 observable,我想知道任何从未到达任何订阅者的元素(例如过滤掉)并据此采取行动。实现这样的目标的最佳方法是什么?

【问题讨论】:

  • 这完全取决于你想让兔子洞走多深......

标签: javascript asynchronous rxjs


【解决方案1】:

选项#1

结合使用发布和函数组合。

var Rx        = require('rx')
    log       = console.log.bind(console),
    source    = Rx.Observable.interval(100).take(100);
    published = source.publish(),
    accepted  = published.where(condition),
    rejected  = published.where(not(condition));

accepted.subscribe(log.bind(undefined, 'accepted: '));
rejected.subscribe(log.bind(undefined, 'rejected: '));

published.connect();

function condition (x) {
  return x % 4 === 0;
}

function not (func) {
  return function () {
    return !func.apply(this, arguments);
  }
}

选项#2

标记(变异)事件并在最后一秒过滤。

var Rx        = require('rx')
    log       = console.log.bind(console),
    source    = Rx.Observable.interval(100).take(100);

source
  .map(toAcceptable)
  .doAction(function (x) {
    x.acceptable = x.acceptable && condition1(x.value);
  })
  .doAction(function (x) {
    x.acceptable = x.acceptable && condition2(x.value);
  })
  .doAction(function (x) {
    log(x.acceptable ? 'accepted:' : 'rejected:', x);
  })
  .subscribe();

function condition1 (x) {
  return x % 4 === 0;
}

function condition2 (x) {
  return x % 3 === 0;
}

function toAcceptable (x) {
  return {
    acceptable: true,
    value: x
  };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 2017-05-17
    • 1970-01-01
    相关资源
    最近更新 更多