Search code examples
javarx-javarx-java2reactivexrx-java3

Convert Publisher<CompletedFileUpload> to Maybe<HttpResponse<?>>


I have the below method

public Maybe<HttpResponse<?>> post(Publisher<CompletedFileUpload> files) {
        MultipartBody.Builder requestBody = MultipartBody.builder();
        return Flowable.fromPublisher(files).flatMap(file -> {
            requestBody
                    .addPart("file", file.getFilename(), MediaType.TEXT_PLAIN_TYPE, file.getBytes())
                    .addPart("id", "asdasdsds");
            return this.iProductClient.post(requestBody.build());
        });
    }

The return type from this.iProductClient.post(requestBody.build()); is Maybe<HttpResponse<?>>

How can I convert the below code to return Maybe<HttpResponse<?>>, currently the below method has error

return Flowable.fromPublisher(files).flatMap(file -> {
            requestBody
                    .addPart("file", file.getFilename(), MediaType.TEXT_PLAIN_TYPE, file.getBytes())
                    .addPart("id", "asdasdsds");
            return this.iProductClient.post(requestBody.build());
        });

Solution

  • You can use collect and then flatmap in the requrest sending:

    return Flowable.fromPublisher(files)
        .collect(MultipartBody::builder, (requestBody, file) -> {
            requestBody
                .addPart("file", file.getFilename(), MediaType.TEXT_PLAIN_TYPE, file.getBytes())
                .addPart("id", "asdasdsds");
        })
        .flatMapMaybe(requestBody -> iProductClient.post(requestBody.build()))
        ;