如何解决rxJava 如何在能够访问前一个参数的同时进行顺序调用
这是在我的服务器中创建文件记录需要遵循的流程
我需要帮助在 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);
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。