BehaviorSubject

BehaviorSubject - 图1

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

BehaviorSubject - 图2

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


演示

1. let disposeBag = DisposeBag()
2. let subject = BehaviorSubject(value: "?")

4. subject
5. .subscribe { print("Subscription: 1 Event:", $0) }
6. .disposed(by: disposeBag)

8. subject.onNext("?")
9. subject.onNext("?")

11. subject
12. .subscribe { print("Subscription: 2 Event:", $0) }
13. .disposed(by: disposeBag)

15. subject.onNext("?️")
16. subject.onNext("?️")

18. subject
19. .subscribe { print("Subscription: 3 Event:", $0) }
20. .disposed(by: disposeBag)

22. subject.onNext("?")
23. 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(?)