angular - 如何避免 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$
。
解决方案
我的理解是,有些东西会产生 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
来获得结果。
推荐阅读
- postcss - Snowpack 和 postcss 导入?
- git - 我的个人访问令牌仅在有限的时间内缓存,并且密码会贬值,因此我是否应该记住我的令牌?
- java - java - 如何从java中的arraylist创建和打印对象(具有多个属性)?
- python-3.x - flask_restful 字段的自定义日期格式。marshal_with 的日期时间
- python - 为什么 python 使用 Karatsuba 算法进行乘法?FFT不是更快吗?
- java - Viewmodel 不会从 Android Room 更新数据,但成功插入其中
- java - 我可以使用 Firebase Analytics 从 Android 应用获取数据并将其显示在 Java Swing 桌面应用上吗?
- php - PHP读取特定格式的txt文件
- eclipse-plugin - 创建 Eclipse 产品的正确方法
- apache-nifi - 在单个事务中将数据从 database1 复制到 database2 (Apache NiFi)