Home > Back-end >  How to assign nil if network call returns error using Combine
How to assign nil if network call returns error using Combine

Time:04-09

I have a variable with default value. And make a network call to get the value from server. If it returns some error, then I want to make the variable to nil. How can I do this with Future, Promise, Combine?

Asynchronous Programming with Futures and Promises in Swift with Combine Framework

CodePudding user response:

The problem is that the Output of future is Int, so you cannot replace errors with nil, you'd need to replace them with an Int, since the Output of upstream publishers and the input of downstream operators must always match.

You can resolve the issue by mapping the future's Output to Optional<Int>, then you can replace errors with nil.

future
        .receive(on: RunLoop.main)
        .map(Optional.some)
        .replaceError(with: nil)
        .assign(to: &$count)

Also, assign(to:) takes a Published.Publisher as its input, so you need to make your count @Published and pass in its Publisher using $count to assign.

So change the declaration to @Publised var count: Int? = 0.

CodePudding user response:

Replacing the error with a nil value fails because your Future emits an Int value. Change it to an optional Int?:

var count: Int? = 0

    let future = Future<Int?, Error> { promise in
        promise(.failure(DummyError()))
    }.eraseToAnyPublisher()

    init(){
        future
            .receive(on: RunLoop.main) //Getting error
            .replaceError(with: nil)
            .assign(to: &$count)
    }

and assign(to: &) works only with @Published values.

  • Related