【发布时间】:2020-04-03 21:00:01
【问题描述】:
我正在使用 Combine 来编写一个简单的网络爬虫。我正在尝试将返回的数据映射到 HTML 字符串,在每个可能的故障点抛出 ScraperErrors。最后,我想将此字符串传递给我的htmlSubject,即PassthroughSubject<String, ScraperError>,以进行进一步处理。
urlSubscription = URLSession.shared
.dataTaskPublisher(for: url)
.mapError { _ -> ScraperError in // Explicitly stating my failure type is ScraperError
ScraperError.unreachableSite
}
.tryMap { (data, response) -> String in
guard let html = String(data: data, encoding: .utf8) else {
throw ScraperError.readFailed
}
return html
}
.subscribe(htmlSubject) // <-- Not allowed because failure type is now Error
但是,我发现.tryMap 正在将我的ScraperError 擦除为常规的Error,从而阻止我将htmlSubject 链接到末尾:
实例方法 'subscribe' 需要类型 'Error' 和 'ScraperError' 是等价的。
我是否有明显的方法来解决这个问题,或者我是否在概念上被绊倒了?我认为这条链是一个大型函数中的构建块,将<(Data, URLResponse), URLError> 映射到<String, ScraperError>。
感谢任何帮助。
【问题讨论】:
标签: swift reactive-programming combine