I have two functions:
async def f(i):
await asyncio.sleep(1)
return f'f{i}'
async def g(i):
await asyncio.sleep(2)
return f'g{i}'
I want to write a loop that calls them repeatedly and prints the results as they come. Like this imaginary code:
for c in amerge(amap(f, itertools.count()),
amap(g, itertools.count())):
x = await c
print(x)
And the result should be approx f0, f1, g1, f2, f3, g2, f4, f5, g3, ...
My attempt was this:
async def run():
"""bad, always wait for f, then for g"""
for i in itertools.count():
for c in asyncio.as_completed([f(i), g(i)]):
res = await c
print(res)
asyncio.run(run())
But this is not correct, it prints f0, g0, f1, g1, ...
Any ideas?