tree: cb3fe69edf2762eb046a37a335c9b3bba9385fa5 [path history] [tgz]
  1. BUILD.gn
  2. README.md
  3. grpc_async_call_data.cc
  4. grpc_async_call_data.h
  5. grpc_async_dispatcher.cc
  6. grpc_async_dispatcher.h
  7. grpc_async_dispatcher_test_services.proto
  8. grpc_async_dispatcher_unittest.cc
  9. grpc_async_server_streaming_call_data.cc
  10. grpc_async_server_streaming_call_data.h
  11. grpc_async_test_server.cc
  12. grpc_async_test_server.h
  13. grpc_async_unary_call_data.h
  14. grpc_test_util.cc
  15. grpc_test_util.h
  16. scoped_grpc_server_stream.cc
  17. scoped_grpc_server_stream.h
remoting/signaling/grpc_support/README.md

Using GrpcAsyncDispatcher

gRPC++ uses completion queue to handle async operations. It doesn‘t fit well with Chromium’s callback-based async handling paradigm, and it is technically still a blocking API unless you create a new thread to run the queue. gRPC is working on adding callback-based APIs but it won‘t be ready to use in the near future, so we created a GrpcAsyncDispatcher class to help adapting gRPC’s completion queue logic into Chromium's callback paradigm.

Basic usage

class MyClass {
  public:
  MyClass() = default;
  ~MyClass() = default;

  void SayHello() {
    HelloRequest request;
    dispatcher_->ExecuteAsyncRpc(
        base::BindOnce(&HelloService::Stub::AsyncSayHello,
                        base::Unretained(stub_.get())),
        std::make_unique<grpc::ClientContext>(), request,
        base::BindOnce(&MyClass::OnHelloResult,
                        base::Unretained(this)));
  }

  void StartHelloStream() {
    StreamHelloRequest request;
    scoped_hello_stream_ = dispatcher_->ExecuteAsyncServerStreamingRpc(
        base::BindOnce(&HelloService::Stub::AsyncStreamHello,
                      base::Unretained(stub_.get())),
        std::make_unique<grpc::ClientContext>(), request,
        base::BindRepeating(&MyClass::OnHelloStreamMessage,
                            base::Unretained(this)),
        base::BindOnce(&MyClass::OnHelloStreamClosed,
                        base::Unretained(this)));
  }

  void CloseHelloStream() {
    scoped_hello_stream_.reset();
  }

  private:
  void OnHelloResult(const grpc::Status& status,
                     const HelloResponse& response) {
    if (!status.ok()) {
      // Handle error here.
      return;
    }

    // Response is received. Use the result here.
  }

  void OnHelloStreamMessage(const HelloStreamResponse& response) {
    // This will be called every time the server sends back messages
    // through the stream.
  }

  void OnHelloStreamClosed(const grpc::Status& status) {
    if (!status.ok()) {
      // Handle error here.
      return;
    }

    // Stream is closed by the server.
  }

  std::unique_ptr<HelloService::Stub> stub_;
  GrpcAsyncDispatcher dispatcher_;
  std::unique_ptr<ScopedGrpcServerStream> scoped_hello_stream_;
};