一旦网络在 RxSwift 中关闭,再次触发 api

trigger an api again once network goes off in RxSwift

下面是我的代码。我需要多次拨打 api 直到网络信号打开。

 buttonAction.do(onNext: { [weak self] in
                        
                          self?.activity.startAnimating()
                        
                              apiManager.callApi()
                            
                                .do(onNext: { [weak self] in
                                    
                                    self?.activity.stopAnimating()
                                    
                                },onError: { [weak self ] error in
                                    
                                    if let error = error as? NoNetwork {
                                        self?.activity.stopAnimating(errorInfo:error,presentationStyle:.alert)

                                        // here alert will be appear. On click ok button, need to trigger the API() again
                                    }
                                })
                .subscribe().disposed(by:bag)

请注意,您没有说明您希望如何处理任何其他类型的错误,因此下面的代码会忽略它们...如果您想显示所有错误的警报,请删除 filter .

let error = PublishSubject<Error>()

let retry = error
    .filter { [=10=] is NoNetwork }
    .map { [=10=].localizedDescription }
    .flatMapFirst(presentScene(animated: true, scene: { message in
        UIAlertController(title: "Error", message: message, preferredStyle: .alert)
            .scene { [=10=].connectOK() }
    }))
    .share()

Observable.merge(buttonAction, retry)
    .subscribe(onNext: { [activity] in
        activity.startAnimating()
    })
    .disposed(by: bag)

Observable.merge(buttonAction, retry)
    .flatMapFirst {
        apiManager.callApi()
            .catch { error.onNext([=10=]); return .just(()) }
    }
    .subscribe(onNext: { [activity] in
        activity.stopAnimating()
    })
    .disposed(by: bag)

presentScene 函数来自我的 CLE library。在此代码中 activity 是标准 UIActivityIndicatorView 而不是您使用的任何内容。