How to switch between the message in protofile

24 views
Skip to first unread message

rohit

unread,
Jun 18, 2020, 12:10:14 PM6/18/20
to grpc.io
Hello All

I know the functionality of  oneof in protofile to switch  but don't know exactly how to use it . 
I have a problem with similar structure.

//proto 3

//Client side

message A
{
}

message B
{
}


message C
{
  oneof Data
{
    A data1 =20;
    B data2 = 30;
}
}


Now at the server side I will sending one data A or B to be received by Client. Which is the best method to switch between the usage of the data.
How to handle the situation when I have to send both A & B to be received by Client. Any alternative of oneof Because oneof will clear the other message.

Can anyone provide links for the the examples highlighting how to switch between the messages, shall be very helpful,

Thanks and Regards
Rohit

Chengyuan Zhang

unread,
Jun 18, 2020, 5:52:36 PM6/18/20
to grpc.io
This question is best to be asked in protobuf's thread

To switch between setting data A or B in message C, you just use setters for A or B from message C's builder. That last call wins. (FWIW, internally calling the setter for fields in oneof data sets a specifier pointing to it. When you use a getter to read fields in oneof data, the getter always checks the specifier first and only return your value if the specifier points to that field. Otherwise, default value is returned (remember, every field has a default value)).

You cannot set both A and B. Even if you set both of them on the server side, only the one you set lastly will be transmitted to the client side and the client can only read that field's value. This is the semantics of oneof, if you have use case of setting both, don't use oneof, just flatten fields in the message.

For more information of oneof, please see protobuf's documentation.
Reply all
Reply to author
Forward
0 new messages