timeout
timeout 的签名
timeout 的签名func timeout(_ interval: Scheduler.TimeInterval, scheduler: Scheduler, customError: (() -> Failure)? = nil) -> Publishers.Timeout<Self>工作原理
示例:基本用法
import Combine
let publisher = PassthroughSubject<Int, Never>()
let subscription = publisher
.timeout(.seconds(2), scheduler: DispatchQueue.main) // 设置超时时间为 2 秒
.sink(
receiveCompletion: { completion in
switch completion {
case .finished:
print("Publisher completed successfully.")
case .failure(let error):
print("Publisher timed out with error: \(error)")
}
},
receiveValue: { value in
print("Received value: \(value)")
}
)
// 在 3 秒后发送一个值(将导致超时)
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
publisher.send(1)
}
// 立即触发完成事件
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
publisher.send(completion: .finished)
}输出结果:
使用自定义错误
输出结果:
timeout 的注意事项
timeout 的注意事项总结
Last updated