【问题标题】:Using array of observable functions with each items output being the next items input使用可观察函数数组,每个项目输出是下一个项目输入
【发布时间】:2019-04-15 18:47:22
【问题描述】:

我有一个返回 observable 的函数数组,我想使用每个函数 observable 输出作为下一个函数输入按顺序执行,直到数组中的每个函数都被调用。

我怎样才能最好地将它作为一个 observable 返回?

我有一个数组的函数类型:

export type FilterFn = (items: Item[]) => Observable< Item[] >;

【问题讨论】:

  • like 循环遍历函数数组并在调用函数后将 observable 分配给 observable ?
  • 让 observalbe$ =firstObservable functionsArray.forEach(filterFunction=>{observable$=observable$[filterFunction]();})

标签: arrays angular typescript rxjs


【解决方案1】:

您可以使用 Array.reduce 将每个 fn 与 switchMap 运算符链接起来

像这样:

fns.reduce(
  (acc, fn) => acc.pipe( switchMap(fn) ) // switchMap to next fn result
  , of(undefined)                        // initial value to pass to the first fn
)
  .subscribe(result=>{
    console.log(result);
  })

这是playground example for this

【讨论】:

  • @user10103655,更新为使用switchMap,而不是之前的map。请注意,ofimport {of} from 'rxjs'
  • 这看起来很有希望,但“acc”的类型是“FilterFn”,因此我不能做“acc.pipe”,因为它不是可观察的,它是一个返回可观察的 FilterFn。对不起我的标题,它不是可观察的函数,而是返回可观察的函数。
  • @user10103655, acc 将是 Observable&lt;...&gt; 类型,因为我们用 of(undefined) 初始化减少 acc。我在答案中添加了一个带有示例的游乐场。
  • 是的,你是对的,我的错。但是如果我需要像这样传递第二个参数怎么办:export type FilterFn = (items: Item[], somethingElse: string) => Observable;
  • @user10103655,我已经缩短了打印时间,但你仍然可以这样做switchMap(items =&gt; fn(items, 'other', 'values'))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-22
  • 2015-07-14
  • 2013-08-24
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
  • 2012-02-17
相关资源
最近更新 更多