不结合独立的可观察量是不好的做法吗?

Is it bad practice not combining independent observables?

所以,我有三个独立的可观察量:

ngOnInit(){
    first$.subscribe(val => console.log(val));
    second$.subscribe(val => console.log(val));
    third$.subscribe(val => console.log(val));
}

不结合上面的观察结果是不是不好的做法?我是 RxJS 的新手,有很多组合运算符,如 combineLatest 我会使用,但在这种情况下我只想 console.log 新值:

ngOnInit(){
    combineLatest([first$,second$,third$]).subscribe(([firstVal, secondVal, thirdVal]) => {
        console.log([firstVal, secondVal, thirdVal]);
    })
}

这里的问题是三个可观察对象中只有一个必须发出一个新值来执行主体,但是旧值也会记录在控制台中。

所以最好的方法是单独处理它们,但后来我想知道:由于 RxJS 库有很多组合运算符,不组合独立的可观察对象是不是不好的做法?

不,这不是坏习惯。组合运算符仅适用于组合可观察量有意义的场景。如果您的可观察对象彼此独立,那么将它们组合起来实际上是一种不好的做法,这正是您提到的原因:

The problem here would be that only one of the three observables has to emit a new value to execute the body but then also old values are logged in the console.

如果您查看 rxjs documentation for combination operators,您实际上会找到描述以及如何使用每个组合运算符。应该清楚它们的用例是什么意思。

不合并独立的可观察量是不是不好的做法?也许吧,但肯定不总是。

在您的例子中,您只是记录了三个流的输出。你写的东西可以重构

first$.subscribe(val => console.log(val));
second$.subscribe(val => console.log(val));
third$.subscribe(val => console.log(val));

merge(first$, second$, third$).subscribe(console.log);

这两个东西应该总是有相同的输出。这个比那个好吗?好吧,第二种方法的样板代码要少一些。如果所有三个流的消费者并不真正关心值的来源,那么作用于合并的流而不是单独订阅每个流会更简洁。

另一方面,如果您的消费者关心值的来源(这个值是来自 first$ 还是 third$?),那么合并似乎不是个好主意。

car$.subscribe(car => console.log(car.wheel.pressure));
plane$.subscribe(plane => console.log(plane.wings));
train$.subscribe(_ => console.log("CHOO CHOO!"));

merge(car$, plane$, train$).subscribe(val => {
  if(val instanceof Car) console.log(val.wheel.pressure);
  else if(val instanceof Plane) console.log(val.wings);
  else if(val instanceof Train) console.log("CHOO CHOO!");
  else console.err(val);
});

这有点反模式。您正在合并三个流,但随后又将它们分开。分开订阅的方法在这里似乎更清楚。

一般来说,合并流应该增加一些语义值。对于阅读您的代码的任何人来说,组合流在某种程度上是相关的,这应该是一个提示。它们 meant/designed 被统一消费,或者消费者需要两者的价值。