联合发布商与 AnyPublisher
Publisher vs AnyPublisher in Combine
AnyPublisher 在 Combine 中的作用是什么,为什么在许多示例中,包括 WWDC Combine In practice, 27:40 他们 return AnyPublisher,使用 .eraseToAnyPublisher
,而不仅仅是 return出版商?
Use AnyPublisher to wrap a publisher whose type has details you don’t want to expose to subscribers or other publishers.
但是谁能举例说明它在什么地方有用?
Publisher
是一个具有关联类型的协议,而 AnyPublisher
是一个 struct。
尝试转换为 Publisher
,但出现错误
let x = Just(1) as Publisher
Protocol 'Publisher' can only be used as a generic constraint because it has Self or associated type requirements
尽管 Just
是 Publisher
。
不能像AnyPublisher
那样使用Publisher
类型来实现类型擦除。
您可以使用 Publisher
的地方是当您定义一个将泛型作为定义的一部分的函数时。
使用 AnyPublisher
的最常见原因:
Return 来自函数的 Publisher 实例。
使用 Publisher
的最常见原因:
创建协议扩展以创建自定义 Combine 运算符。例如:
extension Publisher {
public func compactMapEach<T, U>(_ transform: @escaping (T) -> U?)
-> Publishers.Map<Self, [U]>
where Output == [T]
{
return map { [=11=].compactMap(transform) }
}
}
Publisher 是一个协议,AnyPublisher 是 Publisher 的具体实现。
AnyPublisher 是一个符合 Publisher 协议的 type-erased 结构。类型擦除允许隐藏有关可能不想向订阅者或下游发布者公开的发布者的详细信息。
注意:
AnyPublisher 没有 send(_:) 运算符,因此无法向该发布者添加新值。
AnyPublisher 在 Combine 中的作用是什么,为什么在许多示例中,包括 WWDC Combine In practice, 27:40 他们 return AnyPublisher,使用 .eraseToAnyPublisher
,而不仅仅是 return出版商?
Use AnyPublisher to wrap a publisher whose type has details you don’t want to expose to subscribers or other publishers.
但是谁能举例说明它在什么地方有用?
Publisher
是一个具有关联类型的协议,而 AnyPublisher
是一个 struct。
尝试转换为 Publisher
,但出现错误
let x = Just(1) as Publisher
Protocol 'Publisher' can only be used as a generic constraint because it has Self or associated type requirements
尽管 Just
是 Publisher
。
不能像AnyPublisher
那样使用Publisher
类型来实现类型擦除。
您可以使用 Publisher
的地方是当您定义一个将泛型作为定义的一部分的函数时。
使用 AnyPublisher
的最常见原因:
Return 来自函数的 Publisher 实例。
使用 Publisher
的最常见原因:
创建协议扩展以创建自定义 Combine 运算符。例如:
extension Publisher {
public func compactMapEach<T, U>(_ transform: @escaping (T) -> U?)
-> Publishers.Map<Self, [U]>
where Output == [T]
{
return map { [=11=].compactMap(transform) }
}
}
Publisher 是一个协议,AnyPublisher 是 Publisher 的具体实现。
AnyPublisher 是一个符合 Publisher 协议的 type-erased 结构。类型擦除允许隐藏有关可能不想向订阅者或下游发布者公开的发布者的详细信息。
注意: AnyPublisher 没有 send(_:) 运算符,因此无法向该发布者添加新值。