我有一个对象,我想发送到多个侦听器/订阅者,所以我签出合并,我看到了两种不同类型的出版商,即NotificationCenter.Publisher和PassThroughSubject。我不明白为什么有人会使用NotificationCenter.Publisher over PassThroughSubject。
我想出了下面的代码,演示了这两种方法。概括地说:
NotificationCenter.Publisher需要具有Notification.Name静态属性Notification.Name/different发布者为同一个Notification.Name发布一个不同类型的对象)NotificationCenter.default (而不是发行者本身)上发布一个新值map闭包中将显式向下转换为使用的类型在什么情况下会有人在PassThroughSubject上使用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!")
}
}发布于 2019-09-07 15:17:29
如果您必须使用使用NotificationCenter的第三方框架。
发布于 2019-09-07 22:40:46
NotificationCenter可以被认为是第一代消息传递系统,而Combine是第二代。它具有运行时开销,需要转换可以存储在Notification中的对象。就我个人而言,在构建iOS 13框架时,我不会使用NotificationCenter,但您确实需要使用它来访问许多只在那里发布的iOS通知。基本上,在我的个人项目中,我会把它当作只读,除非绝对必要。
https://stackoverflow.com/questions/57833890
复制相似问题