如何在 Combine 中将错误类型从 Never 更改为 Error?
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()
我有方法 handleContextObjectDidChangeNotification 做映射。
现在 notificationCenterPublisher 的类型是 AnyPublisher<CoreDataContextObserverState, Never>
但我想让它 AnyPublisher<CoreDataContextObserverState, Error>
并让 handleContextObjectDidChangeNotification 以某种方式指示发生了错误。
我该怎么做?
当故障类型为 Never
:
时,您始终可以使用 setFailureType(to:)
更改 Publisher
的故障类型
notificationCenterPublisher = NotificationCenter.default
.publisher(for: .NSManagedObjectContextObjectsDidChange, object: context)
.map { (notification) -> (CoreDataContextObserverState) in
self.handleContextObjectDidChangeNotification(notification: notification)
}
.setFailureType(to: Error.self) <------------------- add this
.eraseToAnyPublisher()
您可以让您的 handle
方法抛出错误,然后使用 tryMap
:
将其转换为发布者失败
notificationCenterPublisher = NotificationCenter.default
.publisher(for: .NSManagedObjectContextObjectsDidChange, object: context)
.tryMap { try self.handleContextObjectDidChangeNotification([=11=]) }
// ^^^^^^ ^^^
.eraseToAnyPublisher()
这也会将发布者的故障类型更改为 Error
。
notificationCenterPublisher = NotificationCenter.default
.publisher(for: .NSManagedObjectContextObjectsDidChange, object: context)
.map { (notification) -> (CoreDataContextObserverState) in
self.handleContextObjectDidChangeNotification(notification: notification)
}
.eraseToAnyPublisher()
我有方法 handleContextObjectDidChangeNotification 做映射。
现在 notificationCenterPublisher 的类型是 AnyPublisher<CoreDataContextObserverState, Never>
但我想让它 AnyPublisher<CoreDataContextObserverState, Error>
并让 handleContextObjectDidChangeNotification 以某种方式指示发生了错误。
我该怎么做?
当故障类型为 Never
:
setFailureType(to:)
更改 Publisher
的故障类型
notificationCenterPublisher = NotificationCenter.default
.publisher(for: .NSManagedObjectContextObjectsDidChange, object: context)
.map { (notification) -> (CoreDataContextObserverState) in
self.handleContextObjectDidChangeNotification(notification: notification)
}
.setFailureType(to: Error.self) <------------------- add this
.eraseToAnyPublisher()
您可以让您的 handle
方法抛出错误,然后使用 tryMap
:
notificationCenterPublisher = NotificationCenter.default
.publisher(for: .NSManagedObjectContextObjectsDidChange, object: context)
.tryMap { try self.handleContextObjectDidChangeNotification([=11=]) }
// ^^^^^^ ^^^
.eraseToAnyPublisher()
这也会将发布者的故障类型更改为 Error
。