0

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

黑色箭头是流
红色箭头是依赖
这是一大功能
在此处输入图像描述

我需要帮助在 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
                }
                
            }
        });
    }

4

1 回答 1

1

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

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

如果您只需要将响应转换为FinalResultthen 您可以使用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);
            
    });
于 2021-01-07T08:49:56.500 回答