【问题标题】:Flatten nested data-structure in a non-complete RxJS stream在非完整 RxJS 流中展平嵌套数据结构
【发布时间】: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


【解决方案1】:

正如 cmets 中的 @zeroflagl 所建议的那样,toArray 方法非常有效。

由于它仅适用于已完成的 observable,我必须将 swithchMap 发送到 Observable,它使用 take(1) 来获取具有当前存储值的已完成的 observable。

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

【讨论】:

    猜你喜欢
    • 2019-10-31
    • 2022-01-19
    • 2014-05-24
    • 2019-01-21
    • 1970-01-01
    • 2021-05-08
    • 2020-10-04
    • 1970-01-01
    • 2021-11-05
    相关资源
    最近更新 更多