notificationCenterPublisher = NotificationCenter.default
.publisher(for: .NSManagedObjectContextObjectsDidChange, object: context)
.map { (notification) -> (CoreDataContextObserverState) in
self.handleContextObjectDidChangeNotification(notification: notification)
}
.eraseToAnyPublisher()
Run Code Online (Sandbox Code Playgroud)
我有方法handleContextObjectDidChangeNotification 进行映射。
现在 notificationCenterPublisher 是类型AnyPublisher<CoreDataContextObserverState, Never>
但我想做到这一点AnyPublisher<CoreDataContextObserverState, Error>,并让handleContextObjectDidChangeNotification 有某种方法来指示发生了错误。
我怎么做?
当故障类型为以下情况时,您始终可以更改Publisher使用的故障类型:setFailureType(to:)Never
notificationCenterPublisher = NotificationCenter.default
.publisher(for: .NSManagedObjectContextObjectsDidChange, object: context)
.map { (notification) -> (CoreDataContextObserverState) in
self.handleContextObjectDidChangeNotification(notification: notification)
}
.setFailureType(to: Error.self) <------------------- add this
.eraseToAnyPublisher()
Run Code Online (Sandbox Code Playgroud)
您可以handle使用以下方法让您的方法抛出错误并将其转变为发布者失败tryMap:
notificationCenterPublisher = NotificationCenter.default
.publisher(for: .NSManagedObjectContextObjectsDidChange, object: context)
.tryMap { try self.handleContextObjectDidChangeNotification($0) }
// ^^^^^^ ^^^
.eraseToAnyPublisher()
Run Code Online (Sandbox Code Playgroud)
这也将把发布者的失败类型更改为Error。