0

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

arun siva
  • 809
  • 1
  • 7
  • 18

2 Answers2

1

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.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
1

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.

burnsi
  • 6,194
  • 13
  • 17
  • 27
  • Thanks. It works. But I added `@Published` for the `count` variable and now I'm unable to use `assign(to: &)`. It shows "Cannot convert value of type Int? to expected arg type Published.publisher – arun siva Apr 08 '22 at 10:30
  • 2
    Using `assign(to:on:)` won't gonna work like that, since you need to store the `AnyCancellable` returned by the subscription and that operator also has a memory leak unfortunately, hence Apple released `assign(to:)` on iOS 14. – Dávid Pásztor Apr 08 '22 at 10:31
  • @DávidPásztor I stand corrected. – burnsi Apr 08 '22 at 11:35
  • @arunsiva see my edit. – burnsi Apr 08 '22 at 11:37