简体   繁体   English

RxAlamofire取消网络请求

[英]RxAlamofire cancel network request

Below is the example code of RxAlamofire network request. 以下是RxAlamofire网络请求的示例代码。 My problem is that I want to cancel this request whenever the View Controller is dismissed. 我的问题是,无论何时关闭View Controller,我都想取消此请求。

I tried to assign this request to a global variable but requestJSON method returns Observable<(HTTPURLResponse, Any)> type. 我试图将此请求分配给全局变量,但requestJSON方法返回Observable<(HTTPURLResponse, Any)>类型。

Is there a way to handle this request when the View Controller is dismissed? 当View Controller被关闭时,是否有一种方法可以处理此请求?

RxAlamofire.requestJSON(.get, sourceStringURL)
            .debug()
            .subscribe(onNext: { [weak self] (r, json) in
                if let dict = json as? [String: AnyObject] {
                    let valDict = dict["rates"] as! Dictionary<String, AnyObject>
                    if let conversionRate = valDict["USD"] as? Float {
                        self?.toTextField.text = formatter
                            .string(from: NSNumber(value: conversionRate * fromValue))
                    }
                }
                }, onError: { [weak self] (error) in
                    self?.displayError(error as NSError)
            })
            .disposed(by: disposeBag)

If you look at RxAlamofire's code: https://github.com/RxSwiftCommunity/RxAlamofire/blob/8a4856ddd77910950aa2b0f9e237e0209580503c/Sources/RxAlamofire.swift#L434 如果您看一下RxAlamofire的代码: https : //github.com/RxSwiftCommunity/RxAlamofire/blob/8a4856ddd77910950aa2b0f9e237e0209580503c/Sources/RxAlamofire.swift#L434

You'll see that the request is cancelled when the subscription is disposed. 您会看到在取消订阅后该请求被取消。

So as long as your view controller is released (and its dispose bag with it!) when you dismiss it then the request will be cancelled if it hasn't finished of course. 因此,只要您在解除视图控制器时释放它(以及它的处理包!),那么如果请求尚未完成,则该请求将被取消。

As Valérian points out, when your ViewController is dismissed, it and all its properties will be deallocated (if retain count drops to 0 that is). 正如Valérian指出的那样,当您的ViewController被关闭时,它将及其所有属性都被释放(如果保留计数降至0,则为0)。

In particular, when disposeBag property is deallocated, dispose() will be called on all observable sequences added to this bag. 特别是,当disposeBag属性被释放时,将对添加到此bag的所有可观察序列调用dispose() Which, in turn, will call request.cancel() in RxAlamofire implementation. 反过来,它将在RxAlamofire实现中调用request.cancel()

If you need to cancel your request earlier, you can try nil'ing your disposeBag directly. 如果您需要更早取消请求,则可以尝试直接取消处理disposeBag

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM