首页 > 解决方案 > NotificationCenter.Publisher VS PassThroughSubject

问题描述

我有一个对象,我想通过多个侦听器/订阅者发送,所以我查看了 Combine,我看到了 2 种不同类型的发布者,即NotificationCenter.PublisherPassThroughSubject. 我很困惑为什么有人会使用NotificationCenter.Publisherover PassThroughSubject

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

在什么情况下有人会使用NotificationCenter.Publisherover 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!")
    }
}

标签: swiftcombine

解决方案


如果您必须使用使用 NotificationCenter 的 3rd 方框架。


推荐阅读