简体   繁体   English

取消订阅结合框架

[英]Canceling subscription Combine framework

当应用程序在Combine 框架中进入后台时,我们有没有办法取消dataTaskPublisher?

Just send .cancel() to subscriber.只需将.cancel()发送给订阅者。 Here is a demo class这是一个演示类

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
    }
}

If you want to embed the cancellation behavior right into the Combine publisher operator chain then prefix(untilOutputFrom:) can be helpful:如果您想将取消行为直接嵌入到 Combine 发布者运营商链中,那么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)
    })

This starts the the data task but then cancels it if UIApplication.willResignActiveNotification is triggered.这将启动数据任务,但如果UIApplication.willResignActiveNotification被触发,则会取消它。 I don't see many people using this operator, probably because it is poorly named, but it is a common pattern in other reactive frameworks such as ReactiveSwift where the operator is more sensibly named take(until:) .我没有看到很多人使用这个运算符,可能是因为它的名字不好,但它是其他反应式框架中的常见模式,例如 ReactiveSwift,其中运算符更明智地命名为take(until:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM