Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Publisher's error type to Never in Combine

Tags:

ios

swift

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.

like image 348
dev_ios999 Avatar asked Jan 21 '26 11:01

dev_ios999


1 Answers

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.

like image 174
matt Avatar answered Jan 24 '26 04:01

matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!