Gayathri
Gayathri

Reputation: 241

Grpc - Passing different objects into grpc service method

In Chat Service, we get the request from client and send a response based on it. But My scenario is, Server has to send some different objects from a outside method of the class.

For example,

public StreamObserver<SalaryDetails> message(StreamObserver<Employee> responseObserver) {
    observers.add(responseObserver);

    return new StreamObserver<SalaryDetails>() {

        @Override
        public void onCompleted() {
            observers.remove(responseObserver); 
        }

        @Override
        public void onError(Throwable arg0) {
            observers.remove(responseObserver); 
        }

        @Override
        public void onNext(SalaryDetails details) {
            for(StreamObserver<MetricsToVE> observer : observers) {
                **observer.onNext(Employee.newBuilder()
                    .setName("AA")
                    .setCity("B")
                    .build());**
            }
        }
    };
}

In below statement I have hardcoded the fields, how should I pass an object from a different method into the grpc service class.

Upvotes: 1

Views: 4611

Answers (1)

Eric Anderson
Eric Anderson

Reputation: 26434

It depends a bit on why the response values vary:

  1. If the client can predict what the response type is based on the request, then you should probably have the client call different methods based on the type
  2. If the possible options are well-known to the API, then you can use protobuf's oneof.
  3. If the data is arbitrary, then you can use protobuf's Any

It seems like #2 is likely your case.

Upvotes: 0

Related Questions