ios - 在Combine iOS 中获取我的订阅取消状态

标签 ios swift combine

我有这个简单的订阅,我的 subject正在发光的字符串。出于好奇,我想知道我的订阅是否被取消。

Afaik 已取消的管道将不会发送任何完成。
有没有一些方法可以做到这一点?

用例是我可以取消所有订阅并收到一个完成。我可以在哪里清理东西,这可能反射(reflect)了这一点。

PlaygroundPage.current.needsIndefiniteExecution = true

var disposeBag: Set<AnyCancellable> = .init()

let subject = PassthroughSubject<String, Never>()

subject.sink(receiveCompletion: { completion in
    switch completion {
    case .failure(let error):
        print("Failed with: \(error.localizedDescription)")
    case .finished:
        print("Finished")
    }
}) { string in
    print(string)
}.store(in: &disposeBag)

subject.send("A")
disposeBag.map { $0.cancel() }
subject.send("B")

最佳答案

可以通过处理事件

subject
    .handleEvents(receiveCancel: {
        print(">> cancelled")         // << here !!
    })
    .sink(receiveCompletion: { completion in
        switch completion {
        case .failure(let error):
            print("Failed with: \(error.localizedDescription)")
        case .finished:
            print("Finished")
        }
    }) { string in
        print(string)
    }.store(in: &disposeBag)

关于ios - 在Combine iOS 中获取我的订阅取消状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61999061/

相关文章:

swift - 快速组合声明式语法

ios - 关于 block 捕获值和 dispatch_async 的有趣的事情

iOS >> UITableView 具有 2 个不同高度的自定义 UITableViewCell

ios - 在 CollectionView - Swift 中添加第二个自定义单元格

ios - 字典不允许我将字符串附加到它的值

ios - 我可以创建一个可以被多个 ContentView 使用的通用 ObservableObject 类吗?

iOS 11 : How to create folder (directory) in Simulator

ios - 适用于 iOS 的 AWS 开发工具包 : unable to list the files in an S3 bucket

iOS - 如何避免列出已安装的应用程序?

SwiftUI 绑定(bind)默认值(参数标签 '(wrappedValue:)' 不匹配任何可用的重载)