首页 > 解决方案 > 在组合中将发布者的错误类型转换为从不

问题描述

我有一个出版商

var subject = PassthroughSubject<Int, Error>()

我想把它转换成

PassthroughSubject<Int, Never>

有没有办法做到这一点?

编辑 - 更多细节

我不希望发布者完成并且链接的答案不起作用,因为 catch 仍然完成发布者。

标签: iosswiftcombine

解决方案


这是一个使用catch将 an<Int, Error>转换为的示例<Int, Never>

import UIKit
import Combine
class ViewController: UIViewController {
    let subject = PassthroughSubject<Int, Error>()
    var storage = Set<AnyCancellable>()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.subject
            .catch { what in
                Empty(completeImmediately:false)
            }
            .sink {print($0)}
            .store(in: &self.storage)
    }
}

如果你1现在发送到 passthrough 主题,你就1结束了。但是如果你向 passthrough 主题发送一个错误,最后不会有错误到达;管道末端类型为<Int, Never>.

但是,请注意,您将永远无法发送另一个值。这与管道无关;这是因为一旦你通过一个 Subject 发送了一个错误,那个 Subject 就死了。你对此无能为力。


推荐阅读