首页 > 解决方案 > 如何在 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。为什么会这样?如果正确实现,我的代码片段会是什么样子?

标签: typescriptrxjsevent-handling

解决方案


成员应该只能将其作为可观察对象订阅,并且不能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();
                    });
            }
        }

推荐阅读