我想展平从商店获得的值,并在商店发出时将它们作为单个数组发出。
在下面的 No-RxJS 示例中,这在同步版本中非常简单,但我不知道如何使用 RxJS 来做到这一点。
我假设我可以使用 RxJS 来缓冲单个 .next
调用中的值。
我应该使用 RxJS 运算符吗?如果是,那么如何使嵌套数据结构扁平化?
这是我想要实现的目标的一个最小示例。
const store$ = new Rx.BehaviorSubject([])
store$.next([
{
id: 1,
items: [
{
id: 1,
title: 'Foo'
},
{
id: 2,
title: 'Bar'
}
]
},
{
id: 2,
items: [
{
id: 3,
title: 'Fizz'
},
{
id: 4,
title: 'Buzz'
}
]
},
]);
// Desired output: [ "Foo", "Bar", "Fizz", "Buzz" ]
store$
.filter(({length}) => length > 0)
.flatMap(group => group)
.flatMap(({items}) => items)
.map(({title}) => title)
.subscribe(console.log) // Emits separate values :-(
// No-RxJs approach
store$
.filter(({length}) => length > 0)
.map(groups => groups
.map(
({ items }) => items.map(
({ title }) => title
)
)
.reduce((next, acc) => [ ...acc, ...next ], []))
.subscribe(console.log) // Works as expected.
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.1/Rx.js"></script>
最佳答案
根据@zeroflagl的建议在评论中,toArray方法非常有效。
由于它仅适用于已完成的可观察量,因此我必须 swithchMap
到一个可观察量,它使用 take(1)
来获取具有当前存储值的已完成可观察量.
store$
.filter(({ length }) => length > 0)
.switchMap(() => store$.take(1)
.flatMap(group => group)
.flatMap(({ items }) => items)
.map(({ title }) => title)
.toArray()
)
.subscribe(console.log) // Emits flat array
关于angular - 展平非完整 RxJS 流中的嵌套数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41960149/