【问题标题】:RxJS combineLatest on object of Observables?在 Observables 对象上的 RxJS combineLatest?
【发布时间】:2017-03-27 16:41:23
【问题描述】:

我发现自己拥有一个混合了值和可观察对象的对象。比如:

const mixedObject = {
  field1: "Hello",
  field2: Rx.Observable.of('World'),
  field3: Rx.Observable.interval(1000),
};

在此对象上执行combineLatest 之类的操作以获得普通对象流的最佳方法是什么。

例如,我想做这样的事情:

Rx.Observable.combineLatest(mixedObject).subscribe(plainObject => {
  console.log(plainObject.field1, plainObject.field2, plainObject.field3);
  // Outputs: 
  // > Hello World 0
  // > Hello World 1
  // > Hello World 2
});

【问题讨论】:

    标签: rxjs5


    【解决方案1】:

    This is now in RXJS 7.

    const res = combineLatest({ foo: a$, bar: b$, baz: c$ });
    
    res.subscribe(({ foo, bar, baz }) => { console.log(foo, bar, baz); });
    

    注意:Angular 到今天还没有在 v7 上。

    【讨论】:

    【解决方案2】:

    您没有指定 field1 是否始终是一个值,而 field2 和 field3 是可观察的。我会尝试给出一个更通用的解决方案。

    function mixedToSync(obj: any): Observable<any> {
      return Observable.combineLatest(
        Object.keys(obj).map((key: string) => {
          let value = obj[key];
          if(Observable.prototype.isPrototypeOf(value)){
            return value.map(v => ({[key]: v}));
          } else {
            return Observable.of({[key]: value});
          }
        }))
          .map(propsObservables => Object.assign({}, propsObservables));
    }
    

    然后你可以在你的对象上使用它:

     mixedToSync(mixedObject).subscribe(v => console.log(v));
    

    或者为了匹配你的例子:

    mixedToSync(mixedObject).subscribe(v => console.log(v.field1, v.field2, v.field3));
    

    【讨论】:

      猜你喜欢
      • 2019-03-03
      • 1970-01-01
      • 2017-06-25
      • 2020-01-23
      • 2021-02-21
      • 2019-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多