2016-04-19 13 views
0

私はまだRxJSの周りに頭を抱えています。このパターンがあります。私は実行し続けており、もっとエレガントな方法で書きたいと思っています。ObservableのリストからObservableオブジェクトを作成する

Model-View-Intentパターンコンポーネントのモデル部分を実装すると、入力としてアクションを取る関数があり、出力として単一のstate$が返されます。

function model(actions) { 
    const firstProperty$ = 
    const anotherProperty$ = … 

    // Better way to write this? 
    const state$ = Rx.Observable.combineLatest(
     firstProperty$, anotherProperty$, 
     (firstProperty, anotherProperty) => ({ 
      firstProperty, anotherProperty 
     }) 
    ); 
    return state$; 
} 

だから私のmodel方法は、観測の束を計算し、それらの一つ一つは、自分のアプリケーションの状態の一部を表しているアイテムを発します。それは結構です。

しかし、どのように私はきれいに状態を放出する1つの観察可能なものに結合します、各状態は最初の観測可能な名前である単一のオブジェクトですか?

答えて

1

私はhttps://github.com/cyclejs/todomvc-cycleからこのパターンを借り:主な機能には

function model(initialState$, actions){ 
    const mod$ = modifications(actions) 

    return initialState$ 
    .concat(mod$) 
    .scan((state, mod) => mod(state)) 
    .share() 
} 

function modifications(actions){ 
    const firstMod$ = actions.anAction$.map(anAction => (
    state => ({ ...state, 
     firstProperty: anAction.something 
    }) 

    const secondMod$ = actions.otherAction$.map(otherAction => (
    state => ({ ...state, 
     firstProperty: otherAction.something, 
     secondProperty: aComputation(otherAction) 
    }) 

    return Rx.Observable.merge([firstMod$, secondMod$ ]).share() 
} 

を:

const initialState$ = Rx.Observable.from({}) 
const actions = intent(DOM) 
const state$ = model(initialState$, actions).share() 
+0

、おかげで私はまだこの質問に直接答えではかなりわからないんだけど、それにもかかわらず便利です。 –

1

CHadrienからの助けを使用して、ここでは実用的なソリューションです。

const prop1$ = Rx.Observable.of('foo'); 
const prop2$ = Rx.Observable.of('bar'); 
const prop3$ = Rx.Observable.of('baz'); 
const prop4$ = Rx.Observable.of('foobar'); 

function combineObservables(objectOfObservables) { 
    const keys = Object.keys(objectOfObservables); 
    const observables = keys.map(key => objectOfObservables[key]); 
    const combined$ = Rx.Observable.combineLatest(
    observables, (...values) => { 
     var obj = {}; 
     for (let i = 0 ; i < keys.length ; i++) { 
     obj[keys[i]] = values[i]; 
     } 
     return obj; 
    } 
); 
    return combined$; 
} 
combineObservables({prop1$, prop2$, prop3$, prop4$}).subscribe(x => console.log(x)); 

そして結果:

[object Object] { 
    prop1$: "foo", 
    prop2$: "bar", 
    prop3$: "baz", 
    prop4$: "foobar" 
} 
関連する問題