typescript - 如何在 TypeScript 中使用观察者而不是主题来获取事件消息?
问题描述
我正在使用 TypeScript,并且在整个项目中我使用rxjs/Subject来获取事件消息。
这是一个例子:
class Downloader {
const done = new Subject();
download(): Promise<void> {
return downloadSomeFile(...)
.then(() => {
done.next();
});
}
}
在我项目的其他地方,我只是订阅它:
done.subscribe(() => { /* do something fancy */ });
这在技术上是可行的,但我读过这不是设计理念,rxjs
而是直接使用Observable。为什么会这样?如果正确实现,我的代码片段会是什么样子?
解决方案
成员应该只能将其作为可观察对象订阅,并且不能next
从外部触发。知道subscription
一次会发生多个,subject
是更好的选择。
class Downloader {
private _done = new Subject(); // for triggering next
public done = _done.asObservable(); // for subscribers as Observable
public download(): Promise<void> {
return downloadSomeFile(...)
.then(() => {
this._done.next();
});
}
}
推荐阅读
- java - 将 HashMap 转换为具有相同排序的 ArrayList
- r - 在 R 中创建一系列时间数据
- c# - 如何从 iOS customrenderer 访问 PCL 渲染器中的 BindableProperty
- r - R data.table - 在组内部分聚合并执行操作
- xslt - 如何使用 xsl 将文件从 Internet 复制到本地驱动器(文件:复制)
- python - 如何使用pytesseract从pdf文件中的图像中提取文本
- wpf - WPF DataGrid ScrollIntoView 不会滚动到请求的行
- css - 按钮禁用背景颜色内联样式属性 jsx
- javascript - 在 React 中使用 Promise 来等待 JavaScript 映射函数中的函数完成
- php - PHP Zend Doctrine\DBAL\Types\Type 位