取消订阅合并框架

时间:2020-10-19 04:46:10

标签: swiftui combine

在组合框架中应用程序在后台运行时,有没有办法取消dataTaskPublisher?

2 个答案:

答案 0 :(得分:0)

只需将.cancel()发送给订户。这是一个演示课程

class Downloader: ObservableObject{
    var cancellable: AnyCancellable?
    let url: URL

    init(url: URL){
        self.url = url
    }

    func download(){
        cancellable = URLSession.shared.dataTaskPublisher(for: url)
        // ... other operators code
    }
    
    func cancel() {
        self.cancellable?.cancel()
        self.cancellable = nil
    }
}

答案 1 :(得分:0)

如果您想将取消行为直接嵌入到Combine Publisher操作员链中,那么prefix(untilOutputFrom:)可能会有所帮助:

let url: URL = ...
cancellable = URLSession.shared.dataTaskPublisher(for: url)
    .prefix(untilOutputFrom: NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification))
    .sink(receiveCompletion: {
        print($0)
    },receiveValue: {
        print($0)
    })

这将启动数据任务,但是如果触发了UIApplication.willResignActiveNotification,则将其取消。我看不到很多人使用此运算符,可能是因为它的命名不正确,但是它是其他反应式框架(例如ReactiveSwift)中的常见模式,在该框架中,该运算符更明智地命名为take(until:)