I am learning reactive programming using Reactive Streams in Java 9 and also using org.reactivestreams in spring 5.
And i am creating a WebClient using the webflux api spring 5 and spring boot2.
Now, when we set the body of a request using webclient, we can pass on a Reactive Stream(org.reactivestreams in spring 5 to be specific) in the BodyInserters methods as follows:
WebClient.RequestHeadersSpec<?> requestSpec1 = WebClient
.create()
.method(HttpMethod.POST).uri("/getDocs")
.body(BodyInserters
.fromPublisher(Mono.just("data"),
String.class)
);
and from fromPublisher method definition:
Return a BodyInserter that writes the given Publisher.
Parameters: publisher the publisher to stream to the response body elementClass the class of elements contained in the publisher
Now, the publishers and subcribers are also in java 9 reactive streams, and one of the publisher which i have created is like:
import java.util.List;
import java.util.concurrent.SubmissionPublisher;
public class TestReactiveStreams {
public static SubmissionPublisher<String> publisher;
public static void main(String...strings ) {
publisher = new SubmissionPublisher();
TestSubscriber<String> subscriber = new TestSubscriber<String>();
publisher.subscribe(subscriber);
List<String> items = List.of("1","x","2","x","3","x");
System.out.println("Subscribers = "+publisher.getNumberOfSubscribers());
if(publisher.getNumberOfSubscribers() > 0) {
items.stream().forEach(p -> publisher.submit(p));
}
publisher.close();
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Consumed Elements = "+subscriber.consumed);
}
}
Now my question is: Is it possible to use the publisher from TestReactiveStreams in the fromPublisher method of BodyInserters?
I tried the following:
BodyInserter<Publisher<String>, ReactiveHttpOutputMessage> inserter2 = BodyInserters
.fromPublisher(TestReactiveStreams.publisher, SubmissionPublisher.class);
But this is giving the following compile time error:
The method fromPublisher(P, Class<T>) in the type BodyInserters is not applicable for the arguments
(SubmissionPublisher<String>, Class<SubmissionPublisher>)
Please suggest, how can we achieve this?