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

如何使用 RxSwift 和 Alamofire 库调用来自另一个 API 的响应的 API?为了得到一个最终的结果数组。谁能给我举个例子..

【问题讨论】:

    标签: swift alamofire rx-swift


    【解决方案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 */ }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-17
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多