connect

通知 ConnectableObservable 可以开始发出元素了

connect - 图1

ConnectableObservable 和普通的 Observable 十分相似,不过在被订阅后不会发出元素,直到 connect 操作符被应用为止。这样一来你可以等所有观察者全部订阅完成后,才发出元素。


演示

  1. let intSequence = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
  2. .publish()
  3. _ = intSequence
  4. .subscribe(onNext: { print("Subscription 1:, Event: \($0)") })
  5. DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
  6. _ = intSequence.connect()
  7. }
  8. DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
  9. _ = intSequence
  10. .subscribe(onNext: { print("Subscription 2:, Event: \($0)") })
  11. }
  12. DispatchQueue.main.asyncAfter(deadline: .now() + 6) {
  13. _ = intSequence
  14. .subscribe(onNext: { print("Subscription 3:, Event: \($0)") })
  15. }

输出结果:

  1. Subscription 1:, Event: 0
  2. Subscription 1:, Event: 1
  3. Subscription 2:, Event: 1
  4. Subscription 1:, Event: 2
  5. Subscription 2:, Event: 2
  6. Subscription 1:, Event: 3
  7. Subscription 2:, Event: 3
  8. Subscription 3:, Event: 3
  9. Subscription 1:, Event: 4
  10. Subscription 2:, Event: 4
  11. Subscription 3:, Event: 4
  12. Subscription 1:, Event: 5
  13. Subscription 2:, Event: 5
  14. Subscription 3:, Event: 5
  15. Subscription 1:, Event: 6
  16. Subscription 2:, Event: 6
  17. Subscription 3:, Event: 6
  18. ...