Usually, the client can cancel the gRPC call with:
(requestObserver as ClientCallStreamObserver<Request>)
.cancel("Cancelled", null)
However, it is shown in the Javadoc:
CancellableContext withCancellation = Context.current().withCancellation();
// do stuff
withCancellation.cancel(t);
Which one is the "correct" way of cancelling a client call, and letting the server know?
Edit:
To make matters more confusing, there's also ManagedChannel.shutdown*
.
Both are acceptable and appropriate.
clientCallStreamObserver.cancel()
is generally easier as it has less boilerplate. It should generally be preferred. However, it is not thread-safe; it is like normal sending on the StreamObserver. It also requires direct awareness with the RPC; you can't have higher-level code orchestrate the cancellation as it may not even be aware of the RPC.
Use Context
cancellation for thread-safe cancellation and less RPC-aware cancellation. Context cancellation could be used in circumstances similar to thread interruption or Future cancellation. Not that CancellableContext
s should be treated as a resource and must be cancelled eventually to avoid leaking memory. (context.cancel(null)
can be used when the context reaches its "normal" end of life.)