image.png
Subscriber 观察者
Publisher 发布者
Value 被观察的对象的取值
在Swift 5.1中,可以利用@Published 轻松实现观察者模式
假设老王是Subscriber,他的儿子小明的考试成绩是Value,小明的老师是Publisher。
老王想实时观察小明的考试成绩,他就拜托老师,跟老师说“每次有新的考试成绩的时候,就发消息我,我要看看小明有没有好好学习”
上面的场景,就生成了如下代码
import Combine
public class Student {
@Published var score: Int = 0
public init(score: Int) {
self.score = score
}
}
let xiaoMing = Student(score: 0)
let teacher = xiaoMing.$score
var laoWang: AnyCancellable? = teacher.sink { (score) in
if score > 80 {
print("Cake")
} else {
print("Why")
}
}
xiaoMing.score = 50
xiaoMing.score = 90
laoWang = nil
xiaoMing.score = 95
输出结果就是
Why
Why
Cake
生成xiaoMing实例对象的时候,score赋值0,打印第一个Why,
当给score赋值50的时候,打印第二个Why,
当给score赋值90的时候,打印第一个Cake。
此时laoWang觉得小明的成绩上来了,就不想再观察了,laoWang值变为nil,
当score变为95的时候,由于观察者laoWang已经不再观察,以后的成绩变化,就不会再知道了。