I have a generator that continuously submits new data. I want to schedule this work as soon as it comes in. So far however, I can't seem to find a way to use the async for without awaiting each loop. Below is a cut down example, including a dummy async_generator, the one I am using comes from an external library (aiokafka.AIOKafkaConsumer).
import asyncio
async def async_generator():
"""only an example, really a kafka consumer"""
await asyncio.sleep(0.1)
print("submitted record")
yield 42
await asyncio.sleep(0.1)
print("submitted record")
yield 43
async def process_record():
await asyncio.sleep(1)
print("record processed")
async def my_f():
async for _ in async_generator():
await process_record()
print("record processing submitted")
if __name__ == "__main__":
event_loop = asyncio.get_event_loop()
event_loop.run_until_complete(my_f())
I want the output of this to be:
submitted_record
record processing submitted
submitted_record
record processing submitted
record processed
record processed
But instead I get the following as I have to await process_record()
submitted record
record processed
record processing submitted
submitted record
record processed
record processing submitted
I don't think I can use asyncio.gather as the async_generator will continuously produce data and so the gather after the async for wouldn't be reached.