swift - Swift Combine. What is a correct way to return from a block of a timeout handler?
问题描述
I need to implement a handler for a timeout function in Combine. Let's consider the following code structure:
SomeKindOfPublisher<Bool, Never>()
.timeout(timeoutInterval, scheduler: backgroundQueue,
customError: { [weak self] () -> Never in
...
while true {} // This block should not return because of Never
}
My question is how to avoid a weird line while true {}
? I would prefer not to change Never to Error type.
解决方案
Not sure if this is what you want, but the best way I found to handle timeout on publishers with no failure (Failure == Never
) is to force a specific error type and handle timeout error in the completion.
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) })
If think it's strange that the timeout operator doesn't changes the publisher failure type to the custom error on its own, but this is some kind of workaround I found.
推荐阅读
- javascript - HackerRank - 生日蛋糕蜡烛
- sql-server - 没有清除根节点的 CTE 递归
- jquery - 单击“批准”按钮后,如何更改对应于选中复选框的 tr 内 td 的值?
- c# - C# Linq 表达式使用变量的字符串值在 lambda 表达式中设置列名
- windows - windows 操作系统默认会带来一些 VC++ 运行时吗?
- neural-network - 反向传播中的梯度维度
- reactjs - 自动导入总是提示文件类型不正确(tsx -> js),如何解决?
- windows - 如何修改以前的代码以检测部分覆盖的表单
- c# - dll构建成功,但加载dll时执行错误
- python-3.x - 如何将 Essentia 音频包从 Home-brew 链接到 Anaconda venv 以使用 Juypter 调用 Essentia 包