BehaviorSubject

BehaviorSubject - 图1

当观察者对 BehaviorSubject 进行订阅时,它会将源 Observable 中最新的元素发送出来(如果不存在最新的元素,就发出默认元素)。然后将随后产生的元素发送出来。

BehaviorSubject - 图2

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


演示

  1. let disposeBag = DisposeBag()
  2. let subject = BehaviorSubject(value: "?")
  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("?️")
  13. subject
  14. .subscribe { print("Subscription: 3 Event:", $0) }
  15. .disposed(by: disposeBag)
  16. subject.onNext("?")
  17. 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(?️)
  7. Subscription: 1 Event: next(?️)
  8. Subscription: 2 Event: next(?️)
  9. Subscription: 3 Event: next(?️)
  10. Subscription: 1 Event: next(?)
  11. Subscription: 2 Event: next(?)
  12. Subscription: 3 Event: next(?)
  13. Subscription: 1 Event: next(?)
  14. Subscription: 2 Event: next(?)
  15. Subscription: 3 Event: next(?)