PublishSubject

PublishSubject - 图1

PublishSubject 将对观察者发送订阅后产生的元素,而在订阅前发出的元素将不会发送给观察者。如果你希望观察者接收到所有的元素,你可以通过使用 Observablecreate 方法来创建 Observable,或者使用 ReplaySubject

PublishSubject - 图2

如果源 Observable 因为产生了一个 error 事件而中止, PublishSubject 就不会发出任何元素,而是将这个 error 事件发送出来。


演示

  1. let disposeBag = DisposeBag()
  2. let subject = PublishSubject<String>()
  3. subject
  4. .subscribe { print("Subscription: 1 Event:", $0) }
  5. .disposed(by: disposeBag)
  6. subject.onNext("?")
  7. subject.onNext("?")
  8. subject
  9. .subscribe { print("Subscription: 2 Event:", $0) }
  10. .disposed(by: disposeBag)
  11. subject.onNext("?️")
  12. subject.onNext("?️")

输出结果:

  1. Subscription: 1 Event: next(?)
  2. Subscription: 1 Event: next(?)
  3. Subscription: 1 Event: next(?️)
  4. Subscription: 2 Event: next(?️)
  5. Subscription: 1 Event: next(?️)
  6. Subscription: 2 Event: next(?️)