[Result]: failure(Alamofire.AFError.explicitlyCancelled)

Viewed 2114

I am communicating with alamofire. No error occurs when doing the login part, but this error occurs in the register part, but the app does not close. How to do it :(

class DarnerAPIClient {
    static let shared = DarnerAPIClient()
    
    func networkingResult<T: Codable>(from api: DarnerAPI) -> Observable<T> {
        return Observable.create { obs in
            let request = AF.request(URL(string: api.baseURL + api.path)!,
                                     method: api.method!,
                                     parameters: api.parameter,
                                     encoding: api.encoding,
                                     headers: api.header).responseData { response in
                                    debugPrint(response)
                switch response.result {
                case .success(let data):
                    do {
                        let dataToUse: T = try JSONDecoder().decode(T.self, from: data)
                        return obs.onNext(dataToUse)
                    } catch(let error) {
                        return obs.onError(error)
                    }
                case .failure(let error):
                    return obs.onError(error)
                }
            }
            return Disposables.create {
                request.cancel()
            }
        }
    }
}
2 Answers

I was having the same issues took a while to figure it out.

Initially, it was like this and it was not working

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let disposeBag = DisposeBag()

         repository
            .forgotPassword(email: "myemail@gmail.com")
            .observe(on: MainScheduler.instance)
            .subscribe(onSuccess: { (res) in
                print(res)
            }, onFailure: { (error) in
                print(error)
            }).disposed(by: disposeBag)
    }

}

Then I changed it to this and it started working.

class ViewController: UIViewController {

    let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()
       
         repository
            .forgotPassword(email: "myemail@gmail.com")
            .observe(on: MainScheduler.instance)
            .subscribe(onSuccess: { (res) in
                print(res)
            }, onFailure: { (error) in
                print(error)
            }).disposed(by: disposeBag)
    }

}

Self Answer: In my NetWorking Code
I didn't disposed :(

Related