Services
Edit pageLast modified: 28 January 2025Services are the centerpieces of the library. A service is an interface annotated with the @Rpc
annotation, and contains a set of methods and fields that can be executed or accessed remotely. Additionally, a service always has a type of RemoteService
, which can be specified explicitly, or assumed implicitly by the compiler.
note
Note that implicit typing is currently not supported in IDEs, but is a work in progress.
A simple service can be declared as follows:
@Rpc
interface MyService : RemoteService {
suspend fun hello(name: String): String
}
Here we declare the method hello
, that accepts one argument and returns a string. The method is marked with a suspend
modifier, which means that we use coroutines to send RPC requests. Note that for now, only suspend
methods are supported in service interfaces.
tip
Depending on the type of the protocol you use, services may support different features and declarations.
To be able to use a service both in client and server code, the interface should be placed in the common module — kudos to Kotlin Multiplatform.
Now we can implement the service, so server knows how to process incoming requests.
class MyServiceImpl(
override val coroutineContext: CoroutineContext,
) : MyService {
override suspend fun hello(name: String): String {
return "Hello, $name! I'm server!"
}
}
The server will use that implementation to answer the client requests.