DEV Community

myougaTheAxo
myougaTheAxo

Posted on

gRPC on Android: Proto, Channel & Streaming Calls

gRPC on Android: Proto, Channel & Streaming Calls

gRPC provides type-safe, efficient communication using protocol buffers. On Android, gRPC reduces bandwidth and latency for mobile apps.

Defining Proto Services

syntax = "proto3";

package myapp;

service UserService {
  rpc GetUser(UserId) returns (User);
  rpc ListUsers(Empty) returns (stream User);
  rpc UpdateUser(User) returns (Empty);
}

message UserId {
  int32 id = 1;
}

message User {
  int32 id = 1;
  string name = 2;
  string email = 3;
}
Enter fullscreen mode Exit fullscreen mode

Creating gRPC Channel

class GrpcClient(private val host: String, private val port: Int) {
    private val channel = ManagedChannelBuilder
        .forAddress(host, port)
        .usePlaintext()
        .build()

    private val stub = UserServiceGrpc.newBlockingStub(channel)

    fun getUser(id: Int): User {
        return stub.getUser(UserId.newBuilder().setId(id).build())
    }

    fun shutdown() {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS)
    }
}
Enter fullscreen mode Exit fullscreen mode

Server Streaming

val users = mutableListOf<User>()
stub.listUsers(Empty.getDefaultInstance()).forEach { user ->
    users.add(user)
}
Enter fullscreen mode Exit fullscreen mode

Async Calls with Coroutines

suspend fun getUserAsync(id: Int): User = suspendCancellableCoroutine { continuation ->
    val stub = UserServiceGrpc.newAsyncStub(channel)
    stub.getUser(UserId.newBuilder().setId(id).build(), object : StreamObserver<User> {
        override fun onNext(user: User) {
            continuation.resume(user)
        }

        override fun onError(t: Throwable) {
            continuation.resumeWithException(t)
        }

        override fun onCompleted() {}
    })
}
Enter fullscreen mode Exit fullscreen mode

TLS Security

val channel = ManagedChannelBuilder
    .forAddress(host, port)
    .useTransportSecurity()
    .build()
Enter fullscreen mode Exit fullscreen mode

gRPC's binary protocol and streaming capabilities make it ideal for bandwidth-constrained mobile networks. Type safety from proto definitions prevents runtime errors.


8 Android app templates available on Gumroad

Top comments (0)