gpt4 book ai didi

swift - 在 Swift Combine 中, "root"对象总是一个 Subject 吗?

转载 作者:行者123 更新时间:2023-11-28 05:41:34 25 4
gpt4 key购买 nike

Apple 在 Swift Combine 上的 WWDC 视频中,他们总是使用 NSNotificationCenter 作为消息的发布者。但是,Publisher 似乎没有任何实际按需发送消息的能力。该功能似乎在 Subject 中。

我是否正确地假设 Subject 因此必须是任何 Publishers 链的根对象? Apple 提供了两个内置主题:CurrentValueSubjectPassthroughSubject

但我假设我可以使用适当的协议(protocol)编写自己的 Subject

最佳答案

在 Swift Combine 中,Publishers 是一个描述对象的协议(protocol),该对象可以随时间传输值。

Subject 是知道如何命令式发送的扩展发布者。

Publisher 和 Subject 都不是具有实现的具体类;它们都是协议(protocol)。

查看发布者协议(protocol)(并记住主题是扩展发布者):

public protocol Publisher {

associatedtype Output

associatedtype Failure : Error

func receive<S>(subscriber: S) where S : Subscriber, Self.Failure == S.Failure, Self.Output == S.Input
}

要构建自定义发布者,您只需要实现接收函数(并提供类型信息),在该函数中您可以访问订阅者。您将如何从发布者内部向该订阅者发送数据?

为此,我们查看订阅者协议(protocol)以查看可用的内容:

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 提供的两个具体主题具有存储等附加功能。

TL;DR 更改不会发送给发布者,而是发送给订阅者。主题是可以接受一些输入的发布者。

关于swift - 在 Swift Combine 中, "root"对象总是一个 Subject 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56571316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com