Search code examples
iosswiftswift5rx-swiftcompletionhandler

Completion Handler Call N times


In the Button action, I call getLatLongValues method, It will return completion property after API success.

Hear problem is, If I click N th times in button action, getLatLongValues method execute N times.
Like I click the button in 1st time getLatLongValues execute 1 time, I'm click 2nd time not two times getLatLongValues method execute 2 times.

@IBAction func updateDeliveryAddress() {
    guard let address = self.addressTextField.text else { return }
    self.getLatLongValues(address, true, viewModel) { success in
        if success {
            //Success
        } else {
            // Error
        }
    }
}

func getLatLongValues(address: String, setAsDefault: Bool, viewModel:ViewModel, completion: @escaping (_ success: Bool) -> Void) {
    viewModel.location.subscribe(onNext: { [weak self] results in
        guard self != nil else { return }
        if let result = results {
                completion(true) // Success
        }
    }).disposed(by: disposeBag)
    viewModel.fetchLocation(address: address)
}

Why getLatLongValues Execute N times?


Solution

  • because each time you are creating a new subscription. a subscription is not a completion handler that gets executed once.

    viewModel.location.subscribe(onNext: { [weak self] results in
    

    should only be called once, and on each location update, you get the result in the block