2015-09-15 9 views
18

E 'possibile modellare se/o strutture di controllo tramite operatori RxJS. Per quanto ho capito, è possibile utilizzare Observable.filter() per simulare un ramo IF, ma non sono sicuro di simulare un ramo ELSE tramite uno degli operatori Observable.Modellazione RxJS in caso contrario strutture di controllo con operatori Observables

+0

l'hai letto http://xgrommx.github.io/rx-book/content/observable/observable_methods/if.html o http://xgrommx.github.io/rx-book/content/observable/observable_methods/case.html? – xgrommx

+0

@xgrommx, in realtà sto usando il tuo libro Rx per imparare RxJS. Ho perso completamente il parametro 'elseSource' dall'operatore' if'. Grazie mille 'Rx.Observable.if()' ha funzionato come un incantesimo. –

risposta

32

ci sono un paio operatori che si potrebbe usare per emulare questo:

In ordine da molto probabilmente quello che stai chiedendo fo

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

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

grazie per aver fornito questo elenco completo di operatori. Immagino che, a seconda del caso d'uso, posso usare uno di questi operatori per simulare "if/else". Per il mio particolare esempio 'Rx.Observable.if()' ha fatto il trucco. –

+0

Tonnellate più operatori/dettagli nei documenti rxjs: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/observable.md –

+0

Grazie per tutti i dettagli. '' 'Rx.Observable.if()' '' con '' 'elseSource''' ha funzionato. –

Problemi correlati