2016-04-19 50 views
0

我仍然圍繞RxJS進行包裝,並且存在這種我一直在使用的模式,並且我希望找到更優雅的書寫方式。從Observable列表中創建一個Observable對象

實現模型 - 視圖 - 意圖模式組件的模型部分,我有一個函數,將操作作爲輸入返回一個單一的state$ Observable作爲輸出。

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方法計算了一堆可觀的,他們每個人都發出一個代表我的應用程序的狀態的部分項目。沒事兒。

但是,如何將它們乾淨地組合成一個可以發出狀態的observable,每個狀態都是一個單獨的對象,其鍵是最初的可觀察名稱?

回答

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" 
}