发布者(Publisher)与订阅者(Subscriber)
在 Combine 中,有几个重要的组成部分:
发布者:Publisher
订阅者:Subscriber
操作符:Operator
如果您熟悉观察者设计模式,那么Publisher就类似于Observable,Subscriber类似于Observer。
Example 1
Just
只发布一个值即完成,Just
可以认为是函数响应式编程中的Hello World,它很好的展示了Publisher与Subscriber是如何配合完成整个发布订阅过程的。
// 使用Just生成一个Publisher
let publisher1 = Just(42)
// 使用sink操作符生成订阅回调
let subscription1 = publisher1.sink { value in
print("Received value from publisher1: \(value)")
}
Example 2
发布一系列的值
let publisher2 = [1,2,3,4,5].publisher
let subscription2 = publisher2
.sink { value in
print("Received value from publisher2: \(value)")
}
输出:
Received value from publisher2: 1
Received value from publisher2: 2
Received value from publisher2: 3
Received value from publisher2: 4
Received value from publisher2: 5
Example 3
将上例中发布者publisher2发布的值赋值给类实例的属性
class MyClass {
var property: Int = 0 {
didSet {
print("Did set property to \(property)")
}
}
}
let object = MyClass()
let subscription3 = publisher2.assign(to: \.property, on: object)
输出:
Did set property to 1
Did set property to 2
Did set property to 3
Did set property to 4
Did set property to 5