首页 > 解决方案 > 如何避免 RXJS 中的一个可观察变量?

问题描述

我有最后一次轮换的状态:

 public rotate$ = new BehaviorSubject(0);

该主题由以下方式更改:

rotateChanged$.subscribe((rotate: number) => {
    this.rotate$.next(rotate);
});

在哪里rotateChnaged$

const rotateChanged$ = merge(left$, right$).pipe(
        startWith(0),
        scan((acc, value) => acc + value, 0),
        map((rotation) => rotation * rotateAngle),
    );

我需要能够rotate$从外部设置默认值。问题是我可以只使用一个 rxjs 变量来管理轮换吗?现在我使用rotateChanged$and rotate$

标签: angulartypescriptrxjs

解决方案


我的理解是,有些东西会产生 2 个事件流,left$并且right$.

然后rotateChanged$将这两个流转换为一个新的流,通知旋转值。

然后最终有一些消费者想知道订阅的轮换rotate$

首先要考虑的是,您可以使用 aSubject而不是 a,BehaviourSubject因为startWith在构建的管道链中有一个运算符rotateChanged$

其次,让我们试着回答你的问题。我猜你使用 aSubject因为至少有可能不止一个消费者想要知道轮换,而你只需要一个流来提供这些信息(换句话说,你想多播rotation流)。如果是这种情况,您可以share在管道中使用运算符并仅提供作为 API 的rotateChanged$.

在这种情况下,您不需要rotate$,您只需发布rotateChanged$编码如下

const rotateChanged$ = merge(left$, right$).pipe(
        startWith(0),
        scan((acc, value) => acc + value, 0),
        map((rotation) => rotation * rotateAngle),
        share(),
    );

考虑到share,在内部,将使用 aSubject来获得结果。


推荐阅读