I am trying to set up a publisher that will publish a set of integers and at some point may fail. It's slightly contrived but hopefully illustrates principle. Example below.
enum NumberError: Int, Error {
case isFatal, canContinue
}
struct Numbers {
let p = PassthroughSubject<Int, NumberError>()
func start(max: Int) {
let errorI = Int.random(in: 1...max)
for i in (1...max) {
if errorI == i {
p.send(completion: .failure(NumberError.canContinue))
} else {
p.send(i)
}
}
p.send(completion: .finished)
}
}
I then subscribe using:
let n = Numbers()
let c = n.p
.catch {_ in return Just(-1)}
.sink(receiveCompletion: {result in
switch result {
case .failure:
print("Error")
case .finished:
print("Finished")
}
}, receiveValue: {
print($0)
})
n.start(max: 5)
This works in that it replaces errors with -1 but I would then like to continue receiving values. Does anyone know if this is possible? Having read and looked around it seems that flatMap may be the way to go but I can't work out what publisher to use in the closure? Any help much appreciated.