erotsppa
erotsppa

Reputation: 15021

How to change error type from Never to Error in Combine?

notificationCenterPublisher = NotificationCenter.default
            .publisher(for: .NSManagedObjectContextObjectsDidChange, object: context)
            .map { (notification) -> (CoreDataContextObserverState) in
                self.handleContextObjectDidChangeNotification(notification: notification)
            }
            .eraseToAnyPublisher()

I have the method handleContextObjectDidChangeNotification doing the mapping.

Right now notificationCenterPublisher is of type AnyPublisher<CoreDataContextObserverState, Never>

But I want to make it AnyPublisher<CoreDataContextObserverState, Error> and have handleContextObjectDidChangeNotification have some way of indicating an error has occured.

How do I do that?

Upvotes: 2

Views: 2414

Answers (1)

rob mayoff
rob mayoff

Reputation: 385590

You can always change the failure type of a Publisher using setFailureType(to:) when the failure type is Never:

notificationCenterPublisher = NotificationCenter.default
    .publisher(for: .NSManagedObjectContextObjectsDidChange, object: context)
    .map { (notification) -> (CoreDataContextObserverState) in
        self.handleContextObjectDidChangeNotification(notification: notification)
    }
    .setFailureType(to: Error.self) <------------------- add this
    .eraseToAnyPublisher()

You can let your handle method throw an error and turn that into a publisher failure using tryMap:

notificationCenterPublisher = NotificationCenter.default
    .publisher(for: .NSManagedObjectContextObjectsDidChange, object: context)
    .tryMap { try self.handleContextObjectDidChangeNotification($0) }
  // ^^^^^^   ^^^
    .eraseToAnyPublisher()

This will also change the publisher's failure type to Error.

Upvotes: 6

Related Questions