How can subscriber for CurrentValueSubject catch an error

Viewed 245

I'm using CurrentValueSubject to populate a diffabledatasource table.

How can I catch the error?

var strings = CurrentValueSubject<[String], Error>([String]())

viewModel.strings
    .receive(on: DispatchQueue.main)
    .sink(receiveCompletion: {
        print("completion \($0)")
    }, receiveValue: { [weak self] in
        self?.applySnapshot()
    })
    .store(in: &cancellables)

Now receiveCompletion receives the error, but https://www.avanderlee.com/swift/combine-error-handling/ mentions using .catch but I can't see that this works in this case?

1 Answers

You can use .catch to essentially substitute a valid [String] for your Error (probably an empty array in this case):

.receive(on: DispatchQueue.main)
            .catch { error -> Just<[String]> in
                print(error)
                return Just([])
            }
            .sink(receiveValue: { [weak self] _ in
                self?.applySnapshot()
            })
            .store(in: &cancellables)

In this case, replaceError (which the article you linked to also mentioned), may be a simpler approach:

.receive(on: DispatchQueue.main)
            .replaceError(with: [])
            .sink(receiveValue: { [weak self] _ in
                self?.applySnapshot()
            })
            .store(in: &cancellables)

Additional reading: https://www.donnywals.com/catch-vs-replaceerror-in-combine/

Related