我想通过多个函数转换原始值(例如Object)。
这将是逻辑(在同步声明javascript中):
let origin = {foo: 'bar'}
//where those are functions transforming the original value
let transform = [one, two, three]
for(let i in transform) {
origin = transform[i](origin)
}
console.log(origin) //new origin
现在,我想这样做:
目前,这是我的工作代码,其中转换数组被缩减以转换先前的值:
function one(origin) {
origin.bar = 'foo'
return origin
}
const transforms = [one]
const origin = {foo: 'bar'}
Observable.of(origin)
.concatMap(origin => {
return Observable.from(transforms)
.reduce(function(accumulator, transform) {
return transform(accumulator)
}, origin)
.last()
})
.subscribe(modified => console.log(modified))
//outputs: {bar: 'foo', foo: 'bar'}
在这里,如果我使用基本值转换,modified
结果是预期结果。问题是,reduce
无法解析Observables并使用那些无法工作的转换:
//...
function two(origin) {
return new Promise((resolve, reject) => {
origin.foobar = origin.foo + origin.bar ? origin.bar : ''
resolve(origin)
})
}
function three(origin) {
return Observable.of(origin)
}
const transforms = [one, two, three]
如何在应用下一个转换函数之前通过reduce
操作解决上述函数?
我使用的是rxjs@5.0.0-beta.12。
我尝试过使用expand
,但我的Observable会发出每一次变换:
let i = 0
return Observable.of(origin)
.expand(item => {
if (i > transforms.length -1) {
return Observable.empty()
}
let response = transforms[i](item)
if (response instanceof Observable || response instanceof Promise) {
return response
}
return Observable.of(response)
})