How would you implement a 'fan-out, fan-in' pattern using multiple async generators consumed concurrently and merged into one stream?
Short answer
Launch multiple async generators as separate tasks pushing their results into a shared asyncio.Queue (or use asyncio.as_completed on wrapped tasks), then consume the merged queue with a single async generator — producing a unified stream where results appear in whatever order…
Advertisement
AModel answer
Launch multiple async generators as separate tasks pushing their results into a shared asyncio.Queue (or use asyncio.as_completed on wrapped tasks), then consume the merged queue with a single async generator — producing a unified stream where results appear in whatever order they actually complete, not in source order.
async def merge(*sources):
queue = asyncio.Queue()
async def pump(source):
async for item in source:
await queue.put(item)
await queue.put(_DONE)
tasks = [asyncio.create_task(pump(s)) for s in sources]
remaining = len(tasks)
while remaining:
item = await queue.get()
if item is _DONE:
remaining -= 1
else:
yield itemReal-world example
Merging live updates from multiple independent async data sources (e.g., several websocket feeds) into one unified event stream.
Likely follow-ups
- What sentinel or signaling mechanism would you use to know when ALL source generators have finished?
Related topics