Swift: Grouping Futures while making them wait util the previous Promise is fulfilled using Combine

364 views Asked by At

Suppose we've three Futures each wrapping an asynchronous call & each depends on the previous Promise to be fulfilled. Ideally, I'd like to have all these get executed only when the subscriber is attached. How do we get this going using Combine?

    private func future1() -> Future<Bool, Error> {
        return Future { [weak self] promise in
            self?.task1 { result in
                promise(result)
            }
        }
    }

    private func future2() -> Future<Bool, Error> {
        return Future { [weak self] promise in
            self?.task2 { result in
                promise(result)
            }
        }
    }

    private func future3() -> Future<Bool, Error> {
        return Future { [weak self] promise in
            self?.task3 { result in
                promise(result)
            }
        }
    }


    future1()..
    future2()..
    future3()..
    .sink {..}

1

There are 1 answers

0
New Dev On

Future executes its closure synchronously, so it's usually wrapped in a Deferred, which waits for a subscription before it executes its closure.

This sounds like exactly what you'd need to do.

private func future1() -> AnyPublisher<Bool, Error> {
   Deferred { 
      Future { [weak self] promise in
         self?.task1 { result in
            promise(result)
         }
      }
   }
   .eraseToAnyPublisher()
}

Then, you can use .flatMap to stagger each publisher:

future1()
   .flatMap { result1 in
       // do something with result1
       return future2()
   }
   .flatMap { result2 in
       // do something with result2
       return future3()
   }
   .sink(...)