Search code examples
iosswiftcombine

fire an publisher after another


I want to fire two publishers but second should only fire when first one is complete. I tried it with zip could not achieve it. Following is my code:

    let resetPasscodeConfirmationPublisher = authUseCase.resetPasscodeConfirmation(phoneNumber: phoneNumber, code: pincode, passcode: passcode)
        
    
    let getAuthTokenPublisher = authUseCase.getAccessToken(passcode: passcode)
        
        resetPasscodeConfirmationPublisher.zip(getAuthTokenPublisher).sink { res in
            print(res)
        } receiveValue: { values in
            print(values.0)
            print(values.1)
        }.store(in: &cancellables)

so first, resetPasscodeConfirmationPublisher should run and when it is done and I get some value from it getAuthTokenPublisher should run. Right now I am getting response from getAuthTokenPublisher only and not from the first publisher.


Solution

  • You can use a map operator to do that

    resetPasscodeConfirmationPublisher
        .map { result in
            // do what you need with the result
            return getAuthTokenPublisher
        }
        .switchToLatest()
        .sink(
            receiveCompletion: { completion in
    
            },
            receiveValue: { value in
    
            }
        )
        .store(in: &cancellables)