使用 Combine in Swift with removeDuplicated() 处理通知有时不会缓存通知

Handle notifications with Combine in Swift with removeDuplicated() sometimes does not cache notifications

我在捕捉来自默认 NotificationCenter 的通知时遇到问题。有时根本收不到。

下面的代码示例:

NotificationCenter.default.publisher(for: Notifications.userNotification)
    .removeDuplicates()
    .receive(on: DispatchQueue.main)
    .sink { self.handle(notification: [=11=]) }
    .store(in: &subscriptions)

一旦我删除 .removeDuplicates() 行,它就会开始接收所有通知。 问题是:我真的需要这条线吗?真的是helpful/important吗? 我正在寻找 .removeDuplicates() 用法 NotificationCenter 的好例子,但找不到任何东西。 谁能解释一下,为什么会这样?

更新:

在我的例子中,Notifications 用于应用程序内部的导航。它有 userInfo 字典,其中包含如下信息:["navigateTo" : "viewControllerTypeShoppingCart"]["navigateTo" : "viewControllerTypeWishList"]

removeDuplicates 从 Publisher 输出中删除(毫不奇怪)重复事件——具体来说,是通过 Equatable 检查 (==) 的事件。

例如,

With Notifications,这可能是具有相同 Notification.NameNotifications。但是,如果 userInfo 字典不同,相等性测试将失败。例如:

let n = Notification(name: Notification.Name("test"), object: nil, userInfo: ["test":"hi"])
let n2 = Notification(name: Notification.Name("test2"), object: nil, userInfo: ["test":"hi"])
let n3 = Notification(name: Notification.Name("test"), object: nil, userInfo: ["test2":"hi"])
let n4 = Notification(name: Notification.Name("test"), object: nil, userInfo: nil)
let n5 = Notification(name: Notification.Name("test"), object: nil, userInfo: nil)
print("Equal?", n == n2, n == n3, n4 == n5)

结果:

Equal? false false true

您没有列出任何关于您收到的 Notification 类型的信息,但是如果它是,例如,在没有 userInfo 字典的情况下发生的事件如果信息不同,您将错过任何重复的事件,因为它们看起来像重复的。

有用吗?这取决于您的用例。重要的?一样? 在您的情况下,如果 removeDuplicates 导致不良行为,您应该将其删除。