[转] Combine学习笔记 - Publishers and Subscribers
参考链接: https://github.com/AvdLee/CombineSwiftPlayground6个月前 • 189次点击 • 来自 移动端
标签: Swift
Publishers and Subscribers
- A Publisher publishes values ...
- .. a subscriber subscribes to receive publisher's values
Specifics:
- Publishers are typed to the data and error types they can emit
- A publisher can emit, zero, one or more values and terminate gracefully or with an error of the type it declared.
Example 1
"publish" just one value then complete
let publisher1 = Just(42)
// You need to _subscribe_ to receive values (here using a sink with a closure)
let subscription1 = publisher1.sink { value in
print("Received value from publisher1: \(value)")
}
Example 2
"publish" a series of values immediately
let publisher2 = [1, 2, 3, 4, 5].publisher
let subscription2 = publisher2
.sink { value in
print("Received value from publisher2: \(value)")
}
Example 3
assign publisher values to a property on an object
class MyClass {
var property: Int = 0 {
didSet {
print("Did set property to \(property)")
}
}
}
let publisher2 = [1, 2, 3, 4, 5].publisher
let object = MyClass()
let subscription3 = publisher2.assign(to: \.property, on: object)
上篇笔记说过主要有发布者,订阅者和操作符,其中操作符并不是必须
以上3例都没有使用操作符,因为数据并不需要做其他处理即可被订阅者消费,操作符的主要作用就是做数据处理