如果响应不成功,RXJava 重复请求并继续流

问题描述

我需要向网络服务器发出请求,服务器通常会返回我在流中使用的参考代码。但有时服务器很忙并返回一个错误,表明它很忙,所以我必须稍后重试。

public static Single<List<iIB>> run()
{
    //First retrieve reference code from IB
    return IBRepository.getInstance().getReferenceCode()
                .doOnSuccess(s -> Log.d(AppConstants.AppTag,"Success: " + s))
                .doOnError(s -> Log.d(AppConstants.AppTag,"Error: " + s))

            //Once reference code is retrieved,make second request to get XML report as string
        .flatMap((Function<String,SingleSource<String>>) referenceCode -> IBRepository.getInstance().getXMLReport(referenceCode))
        
        ...
}


/**
 * This method makes the first request to IB to get the reference code for the flex query in case of success
 * Sometimes server is busy and ask to retry the request in a few moments so we return an error indicating the cause
 * @return an observable string containing the reference code to download the XMLParser report in IB
 */
public Single<String> getReferenceCode()
{
    final String REF_CODE = "ReferenceCode";
    final String STATUS = "Status";
    final String FAIL = "Fail";
    final String ERROR_MESSAGE = "ErrorMessage";

    return Single.fromObservable(_Volley.getInstance().postRxVolley(IBConstants.QUERY_REQUEST_URL)
            .flatMap((Function<Result,ObservableSource<String>>) Response::processResultResponse)
            .flatMapSingle((Function<String,SingleSource<String>>) xmlResponse ->
            {
                Document xmlDocument = XMLParser.convertStringToXMLDocument(xmlResponse);

                if(xmlDocument == null)
                    return Single.error(new Throwable("Error with DOM XML Library"));
                else if(!XMLParser.getSingleValueFromTag(xmlDocument,STATUS,0).contains(FAIL))
                    return Single.just(XMLParser.getSingleValueFromTag(xmlDocument,REF_CODE,0));
                else
                    return Single.error(new Throwable(XMLParser.getSingleValueFromTag(xmlDocument,ERROR_MESSAGE,0)));
            }));
}

我想要实现的是,如果该方法返回错误,则在一段时间后重试对 getReferenceCode() 的调用。这可以使用 RxJava 运算符实现吗?

谢谢

解决方法

您可以使用 RxJava2 generalfolder1 |folder2 |fileB generalfolder2 |folder1 |fileA 运算符并设置要重试 api 调用的条件。

您可以查看此博客以供参考

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...