新组合&这里的反应式编程,因此非常感谢您的帮助。
我有以下场景:我想构建一个用户界面,用户可以通过页面上的各种"过滤器"按钮来过滤内容。当用户点击其中一个按钮时,我需要发出API请求来获取数据。
现在,我有一个发布者为我提供这些选择的"状态",我的代码结构如下:
state
.publisher /* sends whenever 'state' updates behind the scenes */
.debounce(for: 1.0, scheduler: DispatchQueue.main)
.map { /* create some URL request */ }
.flatMap {
URLSession.shared.dataTaskPublisher(for: someRequest)
.map { $0.data }
.decode(type: MyResponseType.self, decoder: JSONDecoder())
}.sink(receiveCompletion: { (completion) in
/// cancelled
}) { (output) in
/// go show my results
/// Ideally, this is only called when the most recent API call finishes!
}.store(in: &cancellables)
然而,这个实现在以下场景中有一个错误:如果一个事件通过flatMap触发请求,而随后的事件在网络调用完成之前也这样做,那么我们将调用两次完成处理程序。
最好是,我们在某种程度上取消了内部管道,所以我们只执行具有最新事件的完成处理程序。
当新事件进入管道时,我如何"取消"内部管道(由dataTaskPublisher启动的管道(而不拆除外部管道?
您不需要flatMap
。您需要switchToLatest
。将flatMap
更改为普通的map
,然后在其后面添加.switchToLatest()
。因为switchToLatest
需要匹配故障类型,所以您可能还需要使用mapError
。decode
运算符生成故障类型Error
,因此可以从mapError
到Error
。
示例:
state
.publisher /* sends whenever 'state' updates behind the scenes */
.debounce(for: 1.0, scheduler: DispatchQueue.main)
.map { makeURLRequest(from: $0) }
.map({ someRequest in
URLSession.shared.dataTaskPublisher(for: someRequest)
.map { $0.data }
.decode(type: MyResponseType.self, decoder: JSONDecoder())
})
.mapError { $0 as Error }
.switchToLatest()
.sink(
receiveCompletion: ({ (completion) in
print(completion)
/// cancelled
}),
receiveValue: ({ (output) in
print(output)
/// go show my results
/// Ideally, this is only called when the most recent API call finishes!
}))
.store(in: &cancellables)