RxSwift和alamofire,如何在先前请求到达后发送http请求?

时间:2018-12-22 02:08:00

标签: alamofire rx-swift

我需要在RxSwift和Alamofire情况下发送http请求并同步发送,这意味着...

send(1)...response(1)

-------------------- send(2)...response(2)

-----------------------------------------send(3)...response (3)

这是我的代码

            Observable.from(devicesArray)
            .concatMap { (device) in
                return HTTPRequest.deleteDevice(withDevice: device)
            }.subscribe({ (event) in
                log.debug("Remove device successfully")
            }).disposed(by: self.disposeBag)

和deleteDevice是

func deleteDevice(withDevice device:Device) -> Single<String> {

    return Alamofire.request("http://example.com/\(device.deviceId)", method: .delete, parameters: nil, headers: self.headers()).rx
        .responseJSON()
        .retry(self.retryMaxAttempCount)
        .asSingle()
        .observeOn(SerialDispatchQueueScheduler(qos: .default))
        .map({ (response) in
            guard let json = response.value as? [String: Any] else {
                throw HTTPManagerError.invalidResponse
            }

            guard let resultCode = json["resultCode"] as? String else {
                throw HTTPManagerError.invalidResponse
            }

            if resultCode == "0000" || resultCode == "0101" {
                return resultCode
            } else {
                throw HTTPManagerError.invalidResponse
            }
        })
        .observeOn(MainScheduler.instance)
}

现在,每个并行请求的单个HTTPRequest.deleteDevice函数。

那么我如何让这个请求等到上一个请求完成?

谢谢。

1 个答案:

答案 0 :(得分:0)

这里的关键是制作一个可观察对象数组并将它们连接起来:

// first we create a deleteDevice observable for each item. 
// Remember, they don't actually make a network call until subscribed to and concat only subscribes to each once the previous one is done.
Observable.concat(
    devicesArray.map { deleteDevice(withDevice: $0) }
        .map { $0.asObservable() } // because concat doesn't exist for Singles.
        .map { $0.catchErrorJustReturn("\($0) not deleted.") } // make sure that all deletes will be attempted even if one errors out.
    )
    // the above will emit a string every time a delete finishes.
    // `.toArray()` will gather them together into an array.
    .toArray()
    .subscribe(onNext: { results in

    })
    .disposed(by: disposeBag)