在 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 更改不会发送给发布者,而是发送给订阅者。主题是可以接受某些输入的发布者。