为什么Observable可被两个观察者订阅两次,不是Subject才能被多播吗?

来自官方文档的额例子图片描述

来自官方关于Subject多播的介绍:A "multicasted Observable" passes notifications through a Subject which may have many subscribers, whereas a plain "unicast Observable" only sends notifications to a single Observer.

阅读 5.7k
1 个回答

一个 Observable 是可以被多个 observer 订阅的,只是每个订阅都是一个新的独立的 Observable execution :

each subscribed Observer owns an independent execution of the Observable

可以看下面例子:http://jsbin.com/fufajukutu/1...

const { Observable } = Rx


const clock$ = Observable.interval(1000).take(3);

const observerA = {
  next(v) {
    console.log('A next: ' + v)
  }
}
const observerB = {
  next(v) {
    console.log('B next: ' + v)
  }
}

clock$.subscribe(observerA) // a Observable execution

setTimeout(() => {
  clock$.subscribe(observerB) // another new Observable execution
}, 2000)

/*
 * A next: 0
 * A next: 1
 * A next: 2
 * B next: 0
 * B next: 1
 * B next: 2
 */

如果是同一个 shared Observable execution 的话,B的第一个 emit 的值应该是 2 而不是 0 ,并且只有且仅有一个值 2
下面是用 Subject 写的例子:http://jsbin.com/fufajukutu/2...

const { Observable, Subject } = Rx


const clock$ = Observable.interval(1000).take(3);

const observerA = {
  next(v) {
    console.log('A next: ' + v)
  }
}
const observerB = {
  next(v) {
    console.log('B next: ' + v)
  }
}
const subject = new Subject()
subject.subscribe(observerA)

clock$.subscribe(subject)

setTimeout(() => {
  subject.subscribe(observerB)
}, 2000)

/*
 * A next: 0
 * A next: 1
 * A next: 2
 * B next: 2
 */

由于 Subject 是多播,也就是每个 observer 都 share 同一个 Observable execution 。
所以B的第一个 emit 的值并且只有一个值是 2

See Also

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进