快速结合.从超时处理程序块返回的正确方法是什么?



我需要在 Combine 中实现一个超时函数的处理程序。让我们考虑以下代码结构:

SomeKindOfPublisher<Bool, Never>()
.timeout(timeoutInterval, scheduler: backgroundQueue,
customError: { [weak self] () -> Never in
...
while true {} // This block should not return because of Never
}

我的问题是如何避免奇怪的台词while true {}?我宁愿不将"永不"更改为"错误"类型。

不确定这是否是您想要的,但我发现在没有失败(Failure == Never(的情况下处理发布商超时的最佳方法是强制使用特定的错误类型并在完成过程中处理超时错误。

enum SomeKindOfPublisherError: Error {
case timeout
}
publisher
.setFailureType(to: SomeKindOfPublisherError.self)
.timeout(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) })

如果认为超时运算符不会自行将发布者失败类型更改为自定义错误很奇怪,但这是我发现的某种解决方法。

相关内容

最新更新