Publisher vs AnyPublisher in Combine
Publisher is a protocol and AnyPublisher is a concrete implementation of Publisher.
AnyPublisher is a type-erased struct that conforms the Publisher protocol. Type erasure allows to hide details about the publisher that may not want to expose to subscribers — or downstream publishers.
Note: AnyPublisher does not have a send(_:) operator, so new values cannot be added to that publisher.
Publisher
is a Protocol with associated types, while AnyPublisher
is a struct.
Try casting to Publisher
and you get an error
let x = Just(1) as Publisher
Protocol 'Publisher' can only be used as a generic constraint because it has Self or associated type requirements
This despite the fact that Just
is a Publisher
.
The Publisher
type can't be utilized in the same way as AnyPublisher
to achieve type erasure.
Where you could use Publisher
is when you define a function that has generics as part of the definition.
Most common reason to use AnyPublisher
:
Return an instance of a Publisher from a function.
Most common reason to use Publisher
:
Create a protocol extension to create a custom Combine operator. For example:
extension Publisher {
public func compactMapEach<T, U>(_ transform: @escaping (T) -> U?)
-> Publishers.Map<Self, [U]>
where Output == [T]
{
return map { $0.compactMap(transform) }
}
}