我有一个对象,我想通过多个侦听器/订阅者发送,所以我查看了 Combine,我看到了 2 种不同类型的发布者,即NotificationCenter.Publisher
和PassThroughSubject
. 我很困惑为什么有人会使用NotificationCenter.Publisher
over PassThroughSubject
。
我想出了下面的代码,演示了两种方式。总结一下:
NotificationCenter.Publisher
需要有一个Notification.Name
静态属性- 真的不是那种类型安全的(因为我可以为同一个
Notification.Name
/不同的发布者发布不同类型的对象Notification.Name
) - 需要在
NotificationCenter.default
(而不是发布者本身)上发布新值 map
对闭包中使用的类型的显式向下转换
在什么情况下有人会使用NotificationCenter.Publisher
over PassThroughSubject
?
import UIKit
import Combine
let passThroughSubjectPublisher = PassthroughSubject<String, Never>()
let notificationCenterPublisher = NotificationCenter.default.publisher(for: .name).map { $0.object as! String }
extension Notification.Name {
static let name = Notification.Name(rawValue: "someName")
}
class PassThroughSubjectPublisherSubscriber {
init() {
passThroughSubjectPublisher.sink { (_) in
// Process
}
}
}
class NotificationCenterPublisherSubscriber {
init() {
notificationCenterPublisher.sink { (_) in
// Process
}
}
}
class PassThroughSubjectPublisherSinker {
init() {
passThroughSubjectPublisher.send("Henlo!")
}
}
class NotificationCenterPublisherSinker {
init() {
NotificationCenter.default.post(name: .name, object: "Henlo!")
}
}