Sobes.tech
Junior — Middle

Can you explain the principle of operation of asynchronous generators in programming?

sobes.tech AI

Answer from AI

Asynchronous generators in Python allow creating iterators that can suspend their execution using the await keyword, returning values one by one without blocking the main thread. This is useful for processing data streams or events where you need to wait for asynchronous operations to complete.

Example of an asynchronous generator:

import asyncio

async def async_generator():
    for i in range(3):
        await asyncio.sleep(1)  # simulate an asynchronous operation
        yield i

async def main():
    async for value in async_generator():
        print(value)

asyncio.run(main())

In this example, the async_generator yields values with a delay, without blocking the execution of other tasks.