Composing one complete object from iterator gRPC/protobuf

When using gRPC streaming or in some other cases, it may be necessary to compose one complete object from several others or from an iterator.

Let’s take a look at an example. We have an iterator, received by gRPC stub:

Iterator<ProtoResult> iterator = stub.yourMethod(yourRequest);

And we want to get one complete ProtoResult object, which will be the union of all ProtoResult objects, received from the iterator. This is done like this:

ProtoResult result = null;
if (iterator != null && iterator.hasNext()) {
  ProtoResult.Builder mergedResultBuilder = ProtoResult.newBuilder();
  while (iterator.hasNext()) {
    mergedResultBuilder.mergeFrom(iterator.next());
  }
  result = mergedResultBuilder.build();
}

As you can see, the main method name is mergeFrom(), which is called on the builder’s protobuf object. That’s all.

Telegram channel

If you still have any questions, feel free to ask me in the comments under this article or write me at promark33@gmail.com.

If I saved your day, you can support me 🤝

Leave a Reply

Your email address will not be published. Required fields are marked *