【问题标题】:How to cancel previous request using RxAlamofire?如何使用 RxAlamofire 取消先前的请求?
【发布时间】:2017-12-11 03:29:06
【问题描述】:

我想使用 RxAlamofire 取消之前的请求。
但我不知道在哪里调用取消函数。
我有一个 searchBar,我在函数“textdidchange”中调用 API。
所以,我想取消之前的请求并使用新参数调用 API。
有什么建议可以帮助我吗?
谢谢。

func request(_ method: Alamofire.HTTPMethod, url:String, params:[String:Any] = [:], callback: @escaping (JSON) -> Void) {

    var headers:[String:String] = [String:String]()
    if token.isEmpty == false {
        headers["Authorization"] = "Bearer \(token)"
    }

    let configuration = URLSessionConfiguration.default
    configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
    configuration.timeoutIntervalForRequest = 10.0

    _ = SessionManager(configuration: configuration)
        .rx.responseJSON(method,
                         url,
                         parameters: params,
                         encoding: ((method == .get) ? URLEncoding.default : JSONEncoding.default),
                         headers: headers)
        .subscribeOn(SerialDispatchQueueScheduler.init(qos: .background))
        .subscribe(onNext: { (r, data) in

            let json = JSON(data)

            if json["status"].stringValue == "success" {

                callback(json["responseData"])

            }else {

                callback(json)
            }
        }, onError: { (error) in

            callback(JSON(error))

        })
        .addDisposableTo(ResfulAPIDisposeBag)
}

【问题讨论】:

  • 你可以使用 flatMapLatest
  • 对不起,我是初学者。有什么例子给我吗?谢谢。
  • 在订阅前加flatMapLatest()
  • 成功了吗?
  • 为什么要将用户发起的操作放在后台调度队列中?它不应该在 userInitiated 队列上吗?

标签: ios swift alamofire rx-swift rxalamofire


【解决方案1】:

当您订阅 Observable 时,生成的对象是包含订阅的 Disposable。此一次性用品可以手动处理 (yourSubscription.dispose()),也可以将其添加到 DisposeBag。当 dispose bag 被释放时,它包含的所有 Disposables 都会被释放。在您的代码中,这将是 ResfulAPIDisposeBag

let subscription = Observable<Int>.interval(0.1, scheduler: MainScheduler.instance)
    .debug("manually disposed")
    .subscribe()

subscription.dispose()

或者,使用处理袋:

var disposeBag = DisposeBag()

Observable<Int>.interval(0.1, scheduler: MainScheduler.instance)
    .debug("using a dispose bag")
    .subscribe()
    .disposed(by: disposeBag)

// deallocates the first disposeBag and disposes any Disposables inside
disposeBag = DisposeBag()

注意:.addDisposableTo(_) 在最新版本的 RxSwift 中已弃用,请改用 .disposed(by: _)

【讨论】:

    【解决方案2】:

    我们需要添加一些延迟,这将在输入 X 秒后触发请求,但前提是短语没有改变。

    let searchResults = searchBar.rx.text.orEmpty
        .debounce(0.5, scheduler: MainScheduler.instance)
        .distinctUntilChanged()
        //if search: doesn't finish, the observable is cancelled
        .flatMapLatest { query -> Observable<[Repository]> in
            if query.isEmpty {
                return .just([])
            }
            return search(query)
                .catchErrorJustReturn([])
        }
        .observeOn(MainScheduler.instance)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-08
      • 1970-01-01
      • 2018-11-04
      • 2020-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      相关资源
      最近更新 更多