mosquito / aio-pika

AMQP 0.9 client designed for asyncio and humans.
https://aio-pika.readthedocs.org/
Apache License 2.0
1.18k stars 186 forks source link

Why do we need `await asyncio.Future()` after `await queue.consume()`? #592

Open IgelVV opened 8 months ago

IgelVV commented 8 months ago
async def main() -> None:
    connection = await connect("amqp://guest:guest@localhost/")
    async with connection:
        channel = await connection.channel()

        queue = await channel.declare_queue("hello")

        # Start listening the queue with name 'hello' (What does it exactly do?)
        await queue.consume(on_message, no_ack=True)

        print(" [*] Waiting for messages. To exit press CTRL+C")

        #Why we must keep the loop running? 
        #(for example using  run_forever() in other examples after main())
        await asyncio.Future()

if __name__ == "__main__":
    asyncio.run(main())

What does exactly await queue.consume() do? Why do we need to keep the loop running, it looks like consume() has to. I tried to walk through the code and found creating unavailable tasks or smth like that, but I can't.

I will be very glad if you help me figure it out, thank you in advance. You're making a great library.

nidemidovich commented 6 months ago

This is necessary to prevent the completion of the main execution. await asyncio.Future() switches the event loop to perform another task. Since the result is not directly set in the Future instance, the event loop will execute main forever. Of course, untill you press Ctrl+C