可连接的可观察序列类似于普通观察到的序列,但他们不会开始在订阅以后发出事件,但是,只有当他们调用connect()
方法。这样,你可以让所有需要等待并且想要订阅的观察者订阅一个可连接的可观察序列。
在学习可连接的Observable
时,先来看一下普通的序列
let interval = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
// 每隔一秒就调用一次的Observable
_ = interval
.subscribe(onNext: { print("Subscription: 1, Event: \($0)") })
delay(5) { // 必须手动添加延迟才能订阅
_ = interval
.subscribe(onNext: { print("Subscription: 2, Event: \($0)") })
}
func delay(_ interval: TimeInterval, closure:@escaping () ->Void) {
let delay = DispatchTime.now() + interval // swift 版本的dispatch
DispatchQueue.main.asyncAfter(deadline: delay, execute: closure)
}
publish
将一个源观测序列转换为一个可连接序列。
let intSequence = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
.publish()
_ = intSequence
.subscribe(onNext: { print("Subscription 1:, Event: \($0)") })
delay(2) { _ = intSequence.connect() } // 触发
delay(4) {
_ = intSequence
.subscribe(onNext: { print("Subscription 2:, Event: \($0)") })
}
delay(6) {
_ = intSequence
.subscribe(onNext: { print("Subscription 3:, Event: \($0)") })
}
replay
将一个源观测序列转换为一个可连接序列,并将给新的订阅者发送特点数量的之前的事件
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)") })
} // 弥补之前publish的不足
multicast
将一个源观测序列转换为一个可连接序列,并通过指定的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)") })
}
/*
Subject: 0
Subscription 1:, Event: 0
Subject: 1
Subscription 1:, Event: 1
Subscription 2:, Event: 1
Subject: 2
Subscription 1:, Event: 2
Subscription 2:, Event: 2
*/