[英]Swift, Combine, cancel on the flight and replace with the new request operator
我有這個網絡調用來獲取圖像。
func load() {
guard let url = URL(string: urlString)
else { return }
subscription = URLSession.shared.dataTaskPublisher(for: url)
.map({ UIImage(data: $0.data) })
.replaceError(with: nil)
.receive(on: RunLoop.main)
.sink(receiveValue: { [weak self] in self?.image = $0 })
}
這是由正在填充的文本字段觸發的。 鍵入每個字母后,我希望我的發布者等待執行,比如說 2 秒,除非用戶鍵入另一個字母。 如果發生這種情況,我希望計時器再次重置為 2 秒。
如果同時發送了新請求,是否有任何即時取消操作員?
感謝所有的幫助。
對於反應式庫來說,這是一件非常標准的事情,而且很容易完成。 switchToLatest
操作符是一個神奇的操作符。
@available(iOS 14.0, *)
final class ViewController: UIViewController {
var textField: UITextField!
var image: UIImage?
var cancelBag = Set<AnyCancellable>()
override func viewDidLoad() {
super.viewDidLoad()
textField.textPublisher // this is from the `CombineCocoa` library
.debounce(for: 2, scheduler: RunLoop.main)
.compactMap { makeURL(from: $0) }
.map {
URLSession.shared.dataTaskPublisher(for: $0)
.catch { _ in Empty() } // what do you want to do with loading errors?
}
.switchToLatest()
.map { UIImage(data: $0.data) }
.receive(on: RunLoop.main)
.sink(receiveValue: { [weak self] in self?.image = $0 })
.store(in: &cancelBag)
}
}
func makeURL(from: String?) -> URL? {
// build and return the correct URL for the image request
fatalError()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.