RxJS建模if else使用Observables运算符控制结构

Art*_*anu 27 rxjs

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

pau*_*els 46

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

按照你最想要的顺序排列

划分

//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();
Run Code Online (Sandbox Code Playgroud)

通过...分组

//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);
  });
Run Code Online (Sandbox Code Playgroud)

如果

//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]))
Run Code Online (Sandbox Code Playgroud)

案例(仅适用于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!"))
Run Code Online (Sandbox Code Playgroud)

  • 尽管在文档中找不到它,Observable.if实际上可以在RxJs 5中找到. (4认同)