RxSwift - 递归 Observables?
Posted
技术标签:
【中文标题】RxSwift - 递归 Observables?【英文标题】:RxSwift - Recursive Observables? 【发布时间】:2019-08-19 11:23:48 【问题描述】:学习 RxSwift - 这是我的问题:
我有一个使用活动访问令牌获取数据的网络服务,每当令牌过期时,首先调用令牌生成 api,然后调用当前请求再次运行。这样它就会有一个有效的访问令牌来访问有效的结果。
但我在获取令牌响应然后调用上一个时遇到问题。请求?
所以我尝试添加一个 observable 请求,然后作为响应检查令牌是否无效,然后调用另一个 observable 以返回一个活动令牌,一旦收到令牌,再次调用旧请求。
func apirequest(_ urlConvertible:URLRequestConvertible) -> Observable<[String:AnyObject]>
return Observable.create( observer -> Disposable in
let _ = Alamofire.request(urlConvertible).responseJSON
response in
if isTokenExpired()
self.generateToken().subscribe(onNext: response
self.apirequest(oldRequest)
)
return Disposables.create()
)
我期待任何 Rx 操作员或任何想法尝试?
谢谢
【问题讨论】:
【参考方案1】:我写了一篇关于如何做到这一点的文章:https://medium.com/@danielt1263/retrying-a-network-request-despite-having-an-invalid-token-b8b89340d29
将您的网络调用代码包装成这样:
/// Builds and makes network requests using the token provided by the service. Will request a new token and retry if the result is an unauthorized (401) error.
///
/// - Parameters:
/// - response: A function that sends requests to the network and emits responses. Can be for example `URLSession.shared.rx.response`
/// - tokenAcquisitionService: The object responsible for tracking the auth token. All requests should use the same object.
/// - request: A function that can build the request when given a token.
/// - Returns: response of a guaranteed authorized network request.
public func getData<T>(response: @escaping (URLRequest) -> Observable<(response: HTTPURLResponse, data: Data)>, tokenAcquisitionService: TokenAcquisitionService<T>, request: @escaping (T) throws -> URLRequest) -> Observable<(response: HTTPURLResponse, data: Data)>
return Observable
.deferred tokenAcquisitionService.token.take(1)
.map try request($0)
.flatMap response($0)
.map response in
guard response.response.statusCode != 401 else throw TokenAcquisitionError.unauthorized
return response
.retryWhen $0.renewToken(with: tokenAcquisitionService)
文章和随附的要点展示了如何编写 tokenAcquisitionService
并包含单元测试。
【讨论】:
谢谢丹尼尔 - 会看看。以上是关于RxSwift - 递归 Observables?的主要内容,如果未能解决你的问题,请参考以下文章