swift - NotificationCenter.Publisher VS PassThroughSubject
问题描述
我有一个对象,我想通过多个侦听器/订阅者发送,所以我查看了 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!")
}
}
解决方案
如果您必须使用使用 NotificationCenter 的 3rd 方框架。
推荐阅读
- flutter - 在flutter web上使用mysql1包连接mysql数据库的问题
- matplotlib - 在 matplotlib 图中以更好的质量插入 PNG 图像
- python-3.x - 为什么我的朋友无法连接到我的套接字
- python - Python从目录中的文件中获取元数据
- html - 如何在 jinja2 模板上使用 css 样式表?
- java - 如何计算弹簧测试中弹簧靴加载的次数?
- ruby-on-rails - 如何在 Rails 中提交时设置多个默认表单值?
- javascript - 将 cURL 转换为 Ajax 并返回错误 400
- python - 如何将二进制转换为数字?
- javascript - 如何启动额外的 PM2