【问题标题】:Convert array to sequence of items with flatMap使用 flatMap 将数组转换为项目序列
【发布时间】:2017-07-01 14:01:32
【问题描述】:

在 RxJS 中,我想将我在某个时刻拥有的数组转换为数组中的一系列项目。我找到了两种方法:选项 1 和 2,我猜,做同样的事情:

const obj = { array: [1, 2, 3, 4, 5] };

const observable = Observable.of(obj);

// Option 1
observable.flatMap(x => {
  return Observable.from(x.array);
}).subscribe(console.log);

// Option 2
observable.flatMap(x => x.array).subscribe(console.log);

// Option 3 ?

是否有更好/更好的方式来表达我正在做的事情,我的意思是没有flatMap 运算符?

【问题讨论】:

    标签: rxjs reactive-programming reactivex


    【解决方案1】:

    我认为您几乎已经到达了最短的路径。我可能建议的唯一改进是完全避免使用回调函数:

    const obj = { array: [1, 2, 3, 4, 5] };
    const observable = Observable.of(obj);
    
    observable
      .pluck('array')
      .concatAll() // or mergeAll()
      .subscribe(console.log);
    

    观看现场演示:https://jsbin.com/zosonil/edit?js,console

    【讨论】:

      猜你喜欢
      • 2018-04-08
      • 1970-01-01
      • 2013-05-18
      • 1970-01-01
      • 1970-01-01
      • 2015-12-31
      • 1970-01-01
      • 1970-01-01
      • 2019-11-02
      相关资源
      最近更新 更多