RxJS 建模 if else 控制结构与 Observables 操作符 [英] RxJS modeling if else control structures with Observables operators

查看:43
本文介绍了RxJS 建模 if else 控制结构与 Observables 操作符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to model if/else control structures via RxJS operators. As far as I understood we could use Observable.filter() to simulate an IF branch, but I am not sure if we simulate an ELSE branch via any of the Observable operator.

推荐答案

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

There are a couple operators that you could use to emulate this:

从最有可能的你要求的顺序

In order from most likely what you are asking for

分区

//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 重命名为 iif 在 v6 中

if edit renamed to iif in v6

//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 中可用)

case (Only available in 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!"))

这篇关于RxJS 建模 if else 控制结构与 Observables 操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆