问题描述
是否可以将给定的 AnyPublisher< AnyType,SomeError>
转换为 AnyPublisher< AnyType,Never>
?
Is there a way to transform a given AnyPublisher<AnyType, SomeError>
to AnyPublisher<AnyType, Never>
?
推荐答案
以从不
作为错误类型的发布者意味着它根本不会抛出错误.它将始终提供价值.
A publisher with Never
as error type mean that it can't throw error at all. It will always deliver a value.
要获得一个永远不会抛出错误的发布者,您有两种解决方法:
To obtain a publisher that can never throw errors you have 2 solutions:
1/捕获所有可能的错误:
1/ Catch all possible errors:
let publisher: AnyPublisher<AnyType, SomeError> = //...
publisher.catch { error in
// handle the error here. The `catch` operator requires to
// return a "fallback value" as a publisher
return Just(/* ... */) // as an example
}
2/如果您确定发布者不会抛出任何错误,则可以使用 .assertNoFailure()
,它将转换您的发布者.请注意,通过 .assertNoFailure()
传递错误时,您的应用将立即崩溃.
2/ If you are sure that there no errors can be thrown by the publisher, you can use .assertNoFailure()
, that will convert your publisher. Note that is an error pass through the .assertNoFailure()
, your app will crash immediately.
这篇关于将给定的发布者失败类型设置为“从不合并"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!