NotificationCenter.Publisher VS PassThroughSubject

NotificationCenter.Publisher VS PassThroughSubject

我有一个对象要在多个 listeners/subscribers 中发送,所以我检查了 Combine,我看到了 2 种不同的发布者,即 NotificationCenter.PublisherPassThroughSubject。我很困惑为什么有人会使用 NotificationCenter.Publisher 而不是 PassThroughSubject

我想出了下面的代码,演示了两种方式。总结一下:

在什么情况下有人会使用 NotificationCenter.Publisher 而不是 PassThroughSubject

import UIKit
import Combine

let passThroughSubjectPublisher = PassthroughSubject<String, Never>()
let notificationCenterPublisher = NotificationCenter.default.publisher(for: .name).map { [=11=].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 的第 3 方框架。

NotificationCenter可以认为是第一代消息传递系统,而Combine是第二代。它具有运行时开销,并且需要转换可以存储在 Notification 中的对象。就我个人而言,在构建 iOS 13 框架时,我永远不会使用 NotificationCenter,但您确实需要使用它来访问仅在那里发布的许多 iOS 通知。基本上在我的个人项目中,除非绝对必要,否则我会将其视为只读。