【问题标题】:Handle notifications with Combine in Swift with removeDuplicated() sometimes does not cache notifications在 Swift 中使用带有 removeDuplicated() 的组合处理通知有时不会缓存通知
【发布时间】:2021-04-22 15:50:05
【问题描述】:

我无法从默认 NotificationCenter 捕获通知。有时它根本没有收到。

下面的代码示例:

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

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

更新

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

【问题讨论】:

    标签: swift swiftui combine


    【解决方案1】:

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

    例如,对于Notifications,这可能是Notifications 和相同的Notification.Name。但是,如果 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 导致不良行为,您应该将其删除。

    【讨论】:

    • 感谢您的回答。在我的情况下,通知用于导航到不同的 ViewController。 userInfo 字典包含不同的值,但有时它具有相同的值,因为例如用户导航到同一个视图控制器两次或更多次。
    • 好的。我不确定这是否会改变我的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多