Reputation: 1942
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?
Upvotes: 3
Views: 3479
Reputation: 2091
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
Upvotes: 5