首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NotificationCenter.Publisher对PassThroughSubject

NotificationCenter.Publisher对PassThroughSubject
EN

Stack Overflow用户
提问于 2019-09-07 12:55:25
回答 2查看 1.2K关注 0票数 2

我有一个对象,我想发送到多个侦听器/订阅者,所以我签出合并,我看到了两种不同类型的出版商,即NotificationCenter.PublisherPassThroughSubject。我不明白为什么有人会使用NotificationCenter.Publisher over PassThroughSubject

我想出了下面的代码,演示了这两种方法。概括地说:

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

在什么情况下会有人在PassThroughSubject上使用PassThroughSubject

代码语言:javascript
复制
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!")
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-09-07 15:17:29

如果您必须使用使用NotificationCenter的第三方框架。

票数 3
EN

Stack Overflow用户

发布于 2019-09-07 22:40:46

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57833890

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档