Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Publisher vs AnyPublisher in Combine

Tags:

swift

combine

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?

like image 673
Hamoonist Avatar asked Aug 28 '19 10:08

Hamoonist


People also ask

What are publishers in combine?

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.

What are publishers Swift?

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.

What does eraseToAnyPublisher mean?

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.

Why should I use combine?

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.


1 Answers

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) }
  }
}
like image 169
Gil Birman Avatar answered Sep 28 '22 09:09

Gil Birman