Observer 是 Observable 传递的值的消费者。
所以基本上观察者接收流发出的值。
Subscription 是一个代表一次性资源的对象,通常是 Observable 的执行。
订阅基本上只是某个观察者当前接收数据的“事实”,如果您取消订阅订阅,则流和观察者仍然存在,只是不再连接.
混合了伪代码的现实世界隐喻:报纸
流:这将是报纸的生产链(涉及出版公司创建内容和印刷厂印刷纸张)
const newsPaper$ = Observable.interval(DAILY)
.switchMapTo(date => publishingCompany.createContent(date))
.switchMapTo(content => printingHouse.printPaper(content))
.publish()
.refCount();
观察者:这将是读者/收件人,那个穿着浴袍的人每天早上在他的前院拿起报纸阅读。 p>
const bathrobeGuy = {
next: newsPaper => readPaper(newsPaper),
error: errorMsg => complainAbout(errorMsg), // the bathrobe guy will be so angry, the he unsubscribes the paper
complete: () => subscribeToDifferentNewsPaper()
}
订阅:这是报纸订阅 - 送货员每天早上把报纸扔到每个前院。
// this will activate the "delivery boy"
const paperSubscription = newsPaper$.subscribe(bathrobeGuy);
退订:当浴袍男决定不再需要报纸时,他可以退订报纸,送货员将不再派送任何报纸。然而观察者(浴袍男)和报社仍然存在,只是已经没有任何关系了。
paperSubscription.unsubscribe();