如何使用 RxSwift 和 Alamofire 库调用来自另一个 API 的响应的 API?

Posted

技术标签:

【中文标题】如何使用 RxSwift 和 Alamofire 库调用来自另一个 API 的响应的 API?【英文标题】:How to call an API with the response from another API using RxSwift and Alamofire library? 【发布时间】:2018-02-15 12:30:06 【问题描述】:

为了得到一个最终的结果数组。谁能给我举个例子..

【问题讨论】:

【参考方案1】:

您将使用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 */ 

【讨论】:

以上是关于如何使用 RxSwift 和 Alamofire 库调用来自另一个 API 的响应的 API?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 RxSwift 和 alamofire 获得嵌套 api 调用的响应?

Alamofire/RxSwift 如何在状态码 401 上自动刷新令牌和重试请求

如何使用 RxSwift 和 Alamofire 库调用来自另一个 API 的响应的 API?

使用 RxSwift 将 Alamofire 请求绑定到表视图

结合 Alamofire 和 RxSwift

RxSwift+Alamofire 自定义映射器错误处理