前言
本篇文章将要学习RxSwift
中连接操作符。Connectable Observable
在订阅时不发射事件消息,而是仅当调用它们的connect()
方法时才发射消息,这样就可以等待所有我们想要的订阅者都已经订阅了以后,再开始发出事件消息,这样能保证我们想要的所有订阅者都能接收到事件消息。其实也就是等大家都就位以后,开始发出消息。
在开始学习Connectable Observable
之前,让我们来看一个non-connectable operator
:
let intervar = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
_ = intervar.subscribe(onNext: {print("subscribe:1, event:\($0)")})
delay(5, closure: { (_) in
_ = intervar.subscribe(onNext: {print("subscribe:2, event:\($0)")})
})
Connectable Observable
在RxSwift
中包括了:
publish
将一个源Observable sequence
转变为一个connectable sequence
。
let intervar = Observable<Int>.interval(1, scheduler: MainScheduler.instance).publish()
_ = intervar.subscribe(onNext: {print("subscribe:1, event:\($0)")})
_ = intervar.subscribe(onNext: {print("subscribe:2, event:\($0)")})
intervar.connect()
你可以试试把intervar.connect()
注释掉,会发现并没有任何响应。
replay
将一个正常的sequence
转换成一个connectable sequence
,然后和replaySubject
相似,能接收到订阅之前的事件消息。
let intSequence = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
.replay(5)
_ = intSequence
.subscribe(onNext: { print("Subscription 1:, Event: \($0)") })
delay(2) { _ = intSequence.connect() }
delay(4) {
_ = intSequence
.subscribe(onNext: { print("Subscription 2:, Event: \($0)") })
}
delay(8) {
_ = intSequence
.subscribe(onNext: { print("Subscription 3:, Event: \($0)") })
}
multicast
将一个正常的sequence
转换成一个connectable sequence
,并且通过特性的subject
发送出去,比如PublishSubject
,或者replaySubject
,behaviorSubject
等。不同的Subject
会有不同的结果。
let subject = PublishSubject<Int>()
_ = subject
.subscribe(onNext: { print("Subject: \($0)") })
let intSequence = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
.multicast(subject)
_ = intSequence
.subscribe(onNext: { print("\tSubscription 1:, Event: \($0)") })
delay(2) { _ = intSequence.connect() }
delay(4) {
_ = intSequence
.subscribe(onNext: { print("\tSubscription 2:, Event: \($0)") })
}
delay(6) {
_ = intSequence
.subscribe(onNext: { print("\tSubscription 3:, Event: \($0)") })
}
致谢
如果发现有错误的地方,欢迎评论,感谢!
时间: 2024-10-06 12:02:10