在 Apple 的 WWDC 视频中Swift Combine
,它们总是NSNotificationCenter
用作消息的发布者。但是,aPublisher
似乎没有任何实际按需发送消息的能力。该功能似乎在Subject
.
我是否正确假设Subject
必须是任何链的根对象Publishers
?Apple 提供了两个内置主题:CurrentValueSubject
和PassthroughSubject
.
Subject
但我假设我可以使用适当的协议编写自己的?
在 Swift Combine 中,Publishers是一个协议,它描述了一个可以随时间传输值的对象。
Subject 是一个扩展的发布者,它知道如何强制发送。
Publisher 和 Subject 都不是具有实现的具体类;它们都是协议。
看一下 Publisher 协议(并记住,Subject 是扩展的 Publisher):
public protocol Publisher {
associatedtype Output
associatedtype Failure : Error
func receive<S>(subscriber: S) where S : Subscriber, Self.Failure == S.Failure, Self.Output == S.Input
}
要构建自定义发布者,您只需要实现接收功能(并提供类型信息),您可以在其中访问订阅者。您将如何从发布者内部向该订阅者发送数据?
为此,我们查看订阅者协议以了解可用的内容:
public protocol Subscriber : CustomCombineIdentifierConvertible {
...
/// Tells the subscriber that the publisher has produced an element.
///
/// - Parameter input: The published element.
/// - Returns: A `Demand` instance indicating how many more elements the subcriber expects to receive.
func receive(_ input: Self.Input) -> Subscribers.Demand
}
只要您保存了对已连接的任何/所有订阅者的引用,您的发布者就可以通过调用receive
订阅者轻松地将更改发送到管道中。但是,您必须自己管理订阅者和差异更改。
Subject 的行为相同,但不是将更改流式传输到管道中,它只是提供一个send
函数供其他人调用。Swift 提供的两个具体的 Subjects 具有额外的特性,比如存储。
TL;DR 更改不会发送给发布者,而是发送给订阅者。主题是可以接受某些输入的发布者。