我需要在组合中实现超时函数的处理程序。让我们考虑以下代码结构:
SomeKindOfPublisher<Bool, Never>()
.timeout(timeoutInterval, scheduler: backgroundQueue,
customError: { [weak self] () -> Never in
...
while true {} // This block should not return because of Never
}
Run Code Online (Sandbox Code Playgroud)
我的问题是如何避免出现奇怪的线条while true {}?我不想将 Never 更改为 Error 类型。
不确定这是否是您想要的,但我发现在没有失败的情况下处理发布者超时的最佳方法 ( Failure == Never) 是强制特定的错误类型并在完成时处理超时错误。
enum SomeKindOfPublisherError: Error {
case timeout
}
publisher
.setFailureType(to: SomeKindOfPublisherError.self)
.timeout(.seconds(1), scheduler: backgroundQueue, customError: { .timeout })
.sink(receiveCompletion: {
switch $0 {
case .failure(let error):
// error is SomeKindOfPublisherError.timeout if timeout error occurs
print("failure: \(error)")
case .finished:
print("finished")
}
}, receiveValue: { print($0) })
Run Code Online (Sandbox Code Playgroud)
如果认为超时运算符没有自行将发布者故障类型更改为自定义错误,这很奇怪,但这是我发现的某种解决方法。
| 归档时间: |
|
| 查看次数: |
3931 次 |
| 最近记录: |