How to call an API with the response from another API using RxSwift and Alamofire library?

时间:2018-02-15 12:30:06

标签: swift alamofire rx-swift

How to call an API with the response from another API using RxSwift and Alamofire library? In order to get a final result array. Can anyone suggest me one example..

1 个答案:

答案 0 :(得分:0)

您可以使用flatMapLatest运算符。

firstRequestObservable()
.debug("first request result")
.flatMapLatest { result in
    self.secondRequestObservable(with: result) 
}
.debug("second request result")

每次firstRequestObservable发出next事件时,之前(如果有)secondRequestObservable都会被新请求覆盖。

您可以使用RxAlamofire或将alamofire请求包装到observable中。 我对Alamofire的了解有限,但这是一个基本的例子,没有处理取消请求的可能性:

Observable<YourReturnType>.create { observable in
    Alamofire.request("https://my.api/request").responseJSON { response in
        if let json = response.result.value {
            // you would typically map this json to a relevant model, using Codable perhaps
            observable.onNext(json)
        }

        observable.onCompleted()
    }
    return Disposables.create { /* some code that can cancel the request */ }
}