简体   繁体   中英

Do then and finally with Flowable reactive x Java

Trying to use Flowable, do then, and finally using RxJava3.

public String post(Publisher<CompletedFileUpload> files) {
    return Flowable.fromPublisher(files).doOnNext(file -> {
        MultipartBody requestBody = MultipartBody.builder()
                .addPart("file", file.getFilename(), MediaType.MULTIPART_FORM_DATA_TYPE, file.getBytes())
                .addPart("id", "asdasdsds")
                .build();
    }).doOnComplete((value) -> {
        return this.iProduct.post(requestBody);
    });
}

The above code has error, But what I am trying to achieve is described in the below scenarios

  1. Iterate on files
  2. add file.getFilename() and bytes to requestBody
  3. Then call the this.iProduct.post(requestBody) which returns the string
  4. Finally return the string value

One way to approach this is to:

  1. Gather all emissions that would come out of Publisher<CompletedFileUpload> files with the toList() operator
  2. Construct the request by looping through the list created in in Step 1 using the map() operator.
  3. Post the request and return the resulting String (also using the map() operator.

The scaffolding for this would look something like this:

public String post(Publisher<CompletedFileUpload> files) {
    final Single<MultipartBody> requestSingle = 
        Flowable.fromPublisher(files)
            .toList()
            .map(list -> {
                final MultipartBody.Builder builder = MultipartBody.Builder();

                for(file : list) {
                    builder.addPart(...)
                }

                return builder.build();
            })
            .map(requestBody -> this.iProduct.post(requestBody));

    return requestSingle.blockingGet();
}

There are two things worth noting here:

  • The toList() operator transforms the Flowable into a Single .
  • Your sample mixes asynchronous code (all the Rx stuff) and synchronous code (the post method returns a String as opposed to a deferred operation/value). The Rx operators are helpful ways of transforming from one reactive type to another, but in your case you need a way to bridge into the synchronous world by invoking those asynchronous operations and waiting for the resulting value. This is the reason for the final call to blockingGet() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM