rxJava 如何在能够访问前一个参数的同时进行顺序调用

问题描述

这是在我的服务器中创建文件记录需要遵循的流程

黑色箭头是流动的
红色箭头是依赖
这是一大功能

enter image description here

我需要帮助在 rxjava 中设计它,使它们按顺序发生,而后来的单曲能够获得参考

我可以为每次接任务创建一些单独的

public static Single<byte[]> processData(byte[] fileData))
public static Single<APIResponse> callAPI(String id,byte[] processedData)
public static Single<UploadResponse> uploadData(String url)

这是我的尝试
我尝试使用 flatMap 的 resultSelector,如下所述
Retrofit and RxJava: How to combine two requests and get access to both results?



    private static Single<FinalResult> bigFunction(String id,int type,String jwt,byte[] fileData){

        return processData(fileData).flatMap(new Function<byte[],SingleSource<APIResponse>>() {
            @Override
            public SingleSource<APIResponse> apply(byte[] processedData) throws Throwable {
                return callAPI(id,processedData);
            }
        },new BiFunction<byte[],APIResponse,UploadResponse>() {
            @Override
            public FinalResult apply(byte[] processData,APIResponse apiResponse) throws Throwable {
                if (processData.size() > LIMIT){
                    uploadData(apiResponse.getUrl());  // I am stuck here how to return a FinalResult() after this uploadData() is complete
                }else{
                   return new FinalResult(); // if no need to upload,done
                }
                
            }
        });
    }

解决方法

如果您不需要结果,那么您可以 ignoreElement() 将您的流程转换为 Completable 并使用 toSingleDefault(...) 函数:

uploadData(apiResponse.getUrl())
    .ignoreElement()
    .toSingleDefault(new FinalResult());

如果您只需要将响应转换为 FinalResult,那么您可以使用 map(...)

uploadData(apiResponse.getUrl())
     .map(uploadResponse -> new FinalResult(uploadResponse));

如果您必须将 uploadData(..) 的结果用于任何外部调用或其他任何内容,那么 flatMap() 是您的选择:

uploadData(apiResponse.getUrl())
    .flatMap(uploadResponse -> {
        // do whatever you want with response
        return Single.just(new FinalResult(uploadResponse));
    });

更新:

就您而言,它可以简化:

return processData(fileData)
    .flatMap(processedData -> {
        Single<FinalResult> postProcessing;
        if (processedData.length > LIMIT) {
            postProcessing = uploadData(apiResponse.getUrl())
                                .map(response -> new FinalResult(response));
        } else {
            postProcessing = Single.just(new FinalResult());
        }
        return callAPI(id,processedData)
            .ignoreElement()
            .andThen(postProcessing);
            
    });

相关问答

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