0

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

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 运算符实现吗?

谢谢

4

1 回答 1

0

您可以使用 RxJava2retryWhen运算符并设置要重试 api 调用的条件。

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

于 2021-05-03T02:48:39.677 回答