注意:使用本例中的代码首先应该导入头文件,代码如下:
import RxSwift
Connectable Operators
可连接的Observable
序列类似于普通的Observable
序列,除了当它们被订阅后一开始不发散元素,只有当它们的connect
方法被调用才会发散元素。这样,你可以等待所有的订阅者在可连接的Observable
序列开始发散元素之前订阅它。
在本页的每个例子中都有一个注释掉的方法。�运行例子需要取消注释,停止运行需要注释掉。
在学习关于可连接的Observable
序列的知识之前,让我看一个不是可连接的�操作:
func sampleWithoutConnectableOperators() {
printExampleHeader(#function)
let interval = Observable.interval(1, scheduler: MainScheduler.instance)
_ = interval
.subscribeNext { print("Subscription: 1, Event: \($0)") }
delay(5) {
_ = interval
.subscribeNext { print("Subscription: 2, Event: \($0)") }
}
}
//sampleWithoutConnectableOperators() // Uncomment to run this example; comment to stop running
在指定的调度程序之上,
interval
(间隔)创建一个Observable
序列并且在每个period
(周期)之后发散元素。了解更多
publish
把源Observable
序列转换成一个可连接的Observable
序列。�了解更多
func sampleWithPublish() {
printExampleHeader(#function)
let intSequence = Observable.interval(1, scheduler: MainScheduler.instance)
_ = intSequence
.subscribeNext { print("Subscription: 1, Event: \($0)") }
delay(2) { intSequence.connect() }
delay(4) {
_ = intSequence
.subscribeNext { print("Subscription: 2, Event: \($0)") }
}
delay(6) {
_ = intSequence
.subscribeNext { print("Subscription: 3, Event: \($0)") }
}
}
//sampleWithPublish() // Uncomment to run this example; comment to stop running
调度程序�作为一个抽象机制来执行工作,比如在特定线程或调度队列。�了解等多
replay
把源Observable
序列转换成一个可连接的Observable
序列,并且将重复�发散bufferSize
次。�了解更多
func sampleWithReplayBuffer() {
printExampleHeader(#function)
let intSequence = Observable.interval(1, scheduler: MainScheduler.instance)
.replay(5)
_ = intSequence
.subscribeNext { print("Subscription 1:, Event: \($0)") }
delay(2) { intSequence.connect() }
delay(4) {
_ = intSequence
.subscribeNext { print("Subscription 2:, Event: \($0)") }
}
delay(8) {
_ = intSequence
.subscribeNext { print("Subscription 3:, Event: \($0)") }
}
}
// sampleWithReplayBuffer() // Uncomment to run this example; comment to stop running
multicast
把源Observable
序列转换成一个可连接的Observable
序列,并通过指定的subject
广播发散。
func sampleWithMulticast() {
printExampleHeader(#function)
let subject = PublishSubject()
_ = subject
.subscribeNext { print("Subject: \($0)") }
let intSequence = Observable.interval(1, scheduler: MainScheduler.instance)
.multicast(subject)
_ = intSequence
.subscribeNext { print("\tSubscription 1:, Event: \($0)") }
delay(2) { intSequence.connect() }
delay(4) {
_ = intSequence
.subscribeNext { print("\tSubscription 2:, Event: \($0)") }
}
delay(6) {
_ = intSequence
.subscribeNext { print("\tSubscription 3:, Event: \($0)") }
}
}
//sampleWithMulticast() // Uncomment to run this example; comment to stop running
下一篇: ��十、����错误处理操作-Error Handling Operators(Rx.playground翻译)�