Services
Edit pageLast modified: 28 January 2025To define a service, create a new .proto
file in the proto
folder next to your source sets:
├── build.gradle.kts
├── settings.gradle.kts
└── src
├── main
│ ├── kotlin
│ │ ├── Client.kt
│ │ ├── ImageRecognizer.kt
│ │ └── Server.kt
│ └── resources
│ └── logback.xml
└── proto
└── image-recognizer.proto
Inside the .proto
file define your service:
syntax = "proto3";
message Image {
bytes data = 1;
}
message RecogniseResult {
int32 category = 1;
}
service ImageRecognizer {
rpc recognize(Image) returns (RecogniseResult);
}
This will generate the necessary code, including the most important interfaces: ImageRecognizer
, Image
, RecogniseResult
:
@Grpc
interface ImageRecognizer {
suspend fun recognize(image: Image): RecogniseResult
}
interface RecogniseResult {
val category: Int
companion object
}
interface Image {
val data: ByteArray
companion object
}
You can implement the ImageRecognizer
:
class ImageRecognizerImpl : ImageRecognizer {
override suspend fun recognize(image: Image): RecogniseResult {
val byte = image.data[0].toInt()
delay(100) // heavy processing
val result = RecogniseResult {
category = if (byte == 0) 0 else 1
}
return result
}
}
Here you can also see the usage of the RecogniseResult
interface. To create an instance, use its .invoke()
extension function:
RecogniseResult {
category = 0
}
Limitations
Current known limitations:
No streaming
Only primitive types in messages
Mandatory java and kotlin protoc generation in addition to our codegen
Kotlin/JVM project only
If you encounter other unexpected limitations or bugs, please report them