gpt4 book ai didi

javascript - 从 Observable 列表创建 Observable 对象

转载 作者:行者123 更新时间:2023-12-02 14:44:36 25 4
gpt4 key购买 nike

我仍然对 RxJS 很感兴趣,并且我一直遇到这种模式,并且我想找到一种更优雅的编写方式。

实现模型- View -意图模式组件的模型部分,我有一个函数,它将操作作为输入,并返回单个 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 方法计算了一堆可观察量,每个可观察量都会发出代表我的应用程序状态的一部分的项目。那很好。

但是如何将它们干净地组合成一个发出状态的可观察对象,每个状态都是一个对象,其键是初始可观察名称?

最佳答案

我从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()

关于javascript - 从 Observable 列表创建 Observable 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36712993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com