Skip to content

Instantly share code, notes, and snippets.

@njsmith
Created August 29, 2018 02:55
Show Gist options
  • Save njsmith/272188858b04665721f0f1cf5c0b3764 to your computer and use it in GitHub Desktop.
Save njsmith/272188858b04665721f0f1cf5c0b3764 to your computer and use it in GitHub Desktop.
@asynccontextmanager
async def subscribe(host, port, subscription_info):
# Make connection, with a 'with' block so we make sure to close it eventually
async with await trio.open_tcp_stream(host, port) as stream:
# Subscribe to whatever channel
await msg_send(stream, subscription_info)
# Start heartbeat task
async with trio.open_nursery() as nursery:
nursery.start_soon(heartbeat_sender, stream)
# Done setting up this context manager. Return the message iterator object.
yield receiver(stream)
# Okay, time to tear everything down. Cancel the heartbeat_sender
nursery.cancel_scope.cancel()
# And when we exit the 'with' blocks here it'll close everything else
# Usage:
async with subscribe(host, port, subscription_info) as messages:
async for message in messages:
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment