What is the role of AnyPublisher in Combine, and why in many examples, including inWWDC Combine In practice, 27:40 they return AnyPublisher, using .eraseToAnyPublisher
, and not just return a Publisher?
The Apple Documents says
Use AnyPublisher to wrap a publisher whose type has details you don’t want to expose to subscribers or other publishers.
But can anyone give an example of where it can be useful?
Overview. A publisher delivers elements to one or more Subscriber instances. The subscriber's Input and Failure associated types must match the Output and Failure types declared by the publisher. The publisher implements the receive(subscriber:) method to accept a subscriber.
Swift Publisher is a super-intuitive, all-purpose page layout and desktop publishing app for Mac. It doesn't matter what kind of document you need to layout and print — from brochures and calendars to CD labels and eye-catching, professional business cards — Swift Publisher covers it all.
Use eraseToAnyPublisher() to expose an instance of AnyPublisher to the downstream subscriber, rather than this publisher's actual type. This form of type erasure preserves abstraction across API boundaries, such as different modules.
By adopting Combine, you'll make your code easier to read and maintain, by centralizing your event-processing code and eliminating troublesome techniques like nested closures and convention-based callbacks.
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.
AnyPublisher
:Return an instance of a Publisher from a function.
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) }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With