Hey @Kannan J and @Vy Do
Thanks for your answers, but for clarifications for newbies like me. Getting into more details.
Yes, as @Kannan J mentioned, the created stub for HelloWorldService.sayHello
is expected as it is mentioned in question. The parameter for HelloWorldResponse can be considered as a Consumer of the response (Drawing analogy from Java 8's Consumer methods) which needs to be consuming the response which needs to be sent back to the client. Whereas, Request is also a consumer (again, the same Java 8's Consumer method's analogy) here will be called once a HelloWorldRequest
is received, so we need to define what needs to be done by implementing and returning that.
Here's the sample implementation of the same:
@Override
public StreamObserver<HelloWorldRequest> sayHello(StreamObserver<HelloWorldResponse> responseObserver) {
return new StreamObserver<>() {
@Override
public void onNext(HelloWorldRequest helloWorldRequest) {
String name = helloWorldRequest.getName();
String greeting = null;
if (StringUtils.hasText(name)) {
if (!name.startsWith("Hello"))
greeting = "Hello " + name;
} else {
greeting = "Hello World";
}
if (StringUtils.hasText(name)) {
HelloWorldResponse response = HelloWorldResponse.newBuilder()
.setGreeting(greeting)
.build();
responseObserver.onNext(response);
}
}
@Override
public void onError(Throwable throwable) {
// Handle error
log.error("Error occurred: {}", throwable.getMessage(), throwable);
responseObserver.onError(throwable);
}
@Override
public void onCompleted() {
// Complete the response
log.info("Request completed");
HelloWorldResponse response = HelloWorldResponse.newBuilder()
.setGreeting("Quitting chat , Thank you")
.build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
};
}
Here, I am creating a new StreamObserver for the request , which tells what to do with the incoming messages (since, it is a stream there could be more than one, like a P2P chat). onNext
tells what to do when a message is received, which can be used using the parameter provided for the same. onError
when something breaks, and finally onCompleted
when a streaming connection is closed. Within these methods responseObserver
for sending messages (or emitting messages, analogy from Reactor streams) back to the client.