2

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

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

  • NotificationCenter.Publisher需要有一个Notification.Name静态属性
  • 真的不是那种类型安全的(因为我可以为同一个Notification.Name/不同的发布者发布不同类型的对象Notification.Name
  • 需要在NotificationCenter.default(而不是发布者本身)上发布新值
  • map对闭包中使用的类型的显式向下转换

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

2 回答 2

3

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

于 2019-09-07T15:17:29.533 回答
0

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

于 2019-09-07T22:40:46.123 回答