2015-09-15 9 views
18

RxJS演算子を使用してif/else制御構造をモデル化することは可能ですか? Observable.filter()を使ってIFブランチをシミュレートすることができましたが、ObservableオペレータでELSEブランチをシミュレートするかどうかはわかりません。Observables演算子を使用したRxJSモデリング

+0

あなたはそれhttp://xgrommx.github.io/rx-book/content/observable/observable_methods/if.htmlまたはそれを読みましたhttp://xgrommx.github.io/rx-book/content/observable/observable_methods/case.html? – xgrommx

+0

@xgrommx、実際に私はあなたのRxの本を使ってRxJSを学んでいます。私は 'if'演算子から' elseSource'パラメータを完全に見逃しました。 Rx.Observable.if()が魅力的に働いてくれてありがとう。 –

答えて

32

は、あなたがこれをエミュレートするために使用することができますカップルのオペレータがあります。ほとんどの場合、あなたが

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(); 

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); 
    }); 
foが求めているものから順に

if

//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])) 

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!")) 
+0

この包括的な演算子のリストを提供してくれてありがとう。私はuse caseに応じて、これらの演算子の1つを使って 'if/else'をシミュレートすることができます。私の特定の例では、 'Rx.Observable.if()'がそのトリックを行いました。 –

+0

rxjs docsにもっと多くの演算子/詳細を追加します:https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/observable.md –

+0

すべての詳細をありがとうございます。 '' 'Rx.Observable.if()' 'と' '' elseSource'''がトリックをしました。 –

関連する問題