I'm trying to merge a bunch of asynchronous generators in Python 3.7 while still adding new async generators on iteration. I'm currently using aiostream
to merge my generators:
from asyncio import sleep, run
from aiostream.stream import merge
async def go():
yield 0
await sleep(1)
yield 50
await sleep(1)
yield 100
async def main():
tasks = merge(go(), go(), go())
async for v in tasks:
print(v)
if __name__ == '__main__':
run(main())
However, I need to be able to continue to add to the running tasks once the loop has begun. Something like.
from asyncio import sleep, run
from aiostream.stream import merge
async def go():
yield 0
await sleep(1)
yield 50
await sleep(1)
yield 100
async def main():
tasks = merge(go(), go(), go())
async for v in tasks:
if v == 50:
tasks.merge(go())
print(v)
if __name__ == '__main__':
run(main())
The closest I've got to this is using the aiostream
library but maybe this can also be written fairly neatly with just the native asyncio
standard library.
aiostream
to merge the generators, and you have managed to add to running tasks, then why not retain that solution? Merging a fixed number of tasks is possible, but not trivial using stock asyncio. You can use that implementation as a starting point if you need to add support for additional iterators. – user4815162342 Jul 18 '18 at 11:34aiostream
library"), I got the impression that you solved the problem usingaiostreams
, so I was wondering why you're not satisfied with that solution? – user4815162342 Jul 18 '18 at 11:50