【发布时间】:2017-06-17 00:59:28
【问题描述】:
我想展平从 store 中获取的值,并在 store 发出时将它们作为单个数组发出。
在下面我的 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>
【问题讨论】:
-
问题是流没有完成,所以你不能减少数据。如果您对完成的流感到满意,您可以简单地调用
toArray()。我想知道为什么您将第二个示例称为“No RxJs”。 -
@zeroflagL 很抱歉造成混淆,它依赖原生数组方法来展平数组,这就是主要原因。
-
我明白了。那么未完成的流呢?
-
@zeroflagL 如果我
switchMap到同一个流但使用take(1),它可以工作,如果我没有遗漏任何东西,看起来这就是解决方案。 -
或
.take(4)和.toArray()?
标签: angular ecmascript-6 rxjs rxjs5 ngrx