Search code examples
iosswiftcombine

Converting Publisher's error type to Never in Combine


I have a Publisher

var subject = PassthroughSubject<Int, Error>()

I want to convert it to

PassthroughSubject<Int, Never>

Is there anyway to achieve this ?

Edit - More Details

I do not want the Publisher to complete and the linked answer did not work because catch still completes the publisher.


Solution

  • Here's an example of using catch to turn an <Int, Error> into an <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)
        }
    }
    

    If you send 1 to the passthrough subject now, you get 1 out the end. But if you send an error to the passthrough subject, no error arrives at the end; the pipeline end type is <Int, Never>.

    However, do note that you can then never send another value. This has nothing to do with the pipeline; it's because once you send an error through a Subject, that Subject is dead. There's nothing you can do about that.