3

I am listening in a python thread on a gRPC stream that never ends:

responses = some_grpc_stub.FunctionThatReturnsStream()
for response in responses:
  on_event(response)

I want to do this for a while, and then stop listening, so that on_event isn't called again, possibly before the stream is done.

How do I do that? Is there a correct way to just kill the thread in which this loop is running? Or is there some way to have responses end prematurely so iteration ends and the thread can run to completion?

2
  • Which gRPC Python API are you using? Future or AsyncIO? Commented May 11, 2022 at 22:15
  • I had been using asyncio but I'm willing to use whatever accomplishes this goal. Commented May 12, 2022 at 0:13

1 Answer 1

5

maybe you can consider using cancel()[1]? The streaming call returns an object that is both a Future and an iterator, you can invoke responses.cancel() to cancel it. In practice, this needs to happen in another thread, because the consumption of the iterator blocks.

If you are using AsyncIO API, the invoking a streaming call returns an object that implemented asyncio.Task, and supports cancel [2]. You can still use responses.cancel() to stop a stream.

[1] https://grpc.github.io/grpc/python/grpc.html#grpc.RpcContext.cancel

[2] https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.cancel

Sign up to request clarification or add additional context in comments.

2 Comments

Yep, works! It might be nice to make that a bit clearer in the examples that involve iterating over a stream. If you don't object, lmk, and I might make a PR adding it.
Improvements are always welcomed! Feel free to @ me in the PR.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.