我有一个获得API请求的功能
我还有一个searchBar来搜索服务器数据
我想在用户输入每个字符时取消之前的请求
我搜索关键字" flatMapLatest"。
但我不知道如何使用" flatMapLatest"在我的情况下取消先前的请求
我尝试但是我失败了
对我有任何建议吗?
感谢。
func requestTest(_ method: Alamofire.HTTPMethod, url:String, params:[String:Any] = [:], callback: @escaping (JSON) -> Void) {
var headers:[String:String] = [String:String]()
if user.token.isEmpty == false {
headers["Authorization"] = "Bearer \(user.token)"
}
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
configuration.timeoutIntervalForRequest = timeout
_ = SessionManager(configuration: configuration)
.rx.responseJSON(method,
url,
parameters: params,
encoding: ((method == .get) ? URLEncoding.default : JSONEncoding.default),
headers: headers)
.subscribeOn(SerialDispatchQueueScheduler.init(qos: .background))
.flatMapLatest({ (<#(HTTPURLResponse, Any)#>) -> ObservableConvertibleType in
//I fail to get request.
})
.subscribe(onNext: { (r, data) in
let json = JSON(data)
if json["status"].stringValue == "success" {
callback(json["request"])
}
else {
callback(json)
}
}, onError: { (error) in
callback(JSON(error))
})
.addDisposableTo(DisposeBag)
}
答案 0 :(得分:0)
使用 .switchLatest(),就像那样 -
let responseSubject: PublishSubject<Observable<Response>> = PublishSubject()
let latestResponse: Observable<Response> = responseSubject.switchLatest() // subscribe to it
// call 'responseSubject.onNext(newRequestObservable)' whenever you need a new request