【问题标题】:RxJS modeling if else control structures with Observables operatorsRxJS 建模 if else 使用 Observables 操作符控制结构
【发布时间】:2015-12-12 04:47:09
【问题描述】:

是否可以通过 RxJS 运算符对 if/else 控制结构进行建模。据我了解,我们可以使用 Observable.filter() 来模拟 IF 分支,但我不确定我们是否通过任何 Observable 运算符来模拟 ELSE 分支。

【问题讨论】:

标签: rxjs


【解决方案1】:

您可以使用几个运算符来模拟:

按照您最有可能要求的顺序

partition

//Returns an array containing two Observables
//One whose elements pass the filter, and another whose elements don't

var items = observableSource.partition((x) => x % 2 == 0);

var evens = items[0];
var odds = items[1];

//Only even numbers
evens.subscribe();

//Only odd numbers
odds.subscribe();

// Using RxJS >= 6
const [evens, odds] = partition(observableSource, x => x % 2 == 0);

//Only even numbers
evens.subscribe();

//Only odd numbers
odds.subscribe();

groupBy

//Uses a key selector and equality comparer to generate an Observable of GroupedObservables
observableSource.groupBy((value) => value % 2, (value) => value)
  .subscribe(groupedObservable => {
    groupedObservable.subscribe(groupedObservable.key ? oddObserver : evenObserver);
  });

if edit 在 v6 中重命名为 iif

//Propagates one of the sources based on a particular condition
//!!Only one Observable will be subscribed to!!
Rx.Observable.if(() => value > 5, Rx.Observable.just(5), Rx.Observable.from([1,2, 3]))

// Using RxJS >= 6
iif(() => value > 5, of(5), from([1, 2, 3]))

case(仅在 RxJS 4 中可用)

//Similar to `if` but it takes an object and only propagates based on key matching
//It takes an optional argument if none of the items match
//!!Only one Observable will be subscribed to!!
Rx.Observable.case(() => "blah",
{
  blah : //..Observable,
  foo : //..Another Observable,
  bar : //..Yet another
}, Rx.Observable.throw("Should have matched!"))

【讨论】:

  • 感谢您提供这份完整的运营商列表。我想根据用例,我可以使用这些运算符之一来模拟if/else。对于我的特定示例,Rx.Observable.if() 成功了。
  • 在 rxjs 文档中提供更多运算符/详细信息:github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/…
  • 感谢您提供所有详细信息。 Rx.Observable.if()elseSource 成功了。
  • 尽管在文档中找不到它,但 Observable.if 实际上在 RxJs 5 中可用。
  • @paulpdaniels 如果我们使用 hot observable,groupby 是如何工作的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-23
  • 2018-11-12
  • 2019-10-20
相关资源
最近更新 更多