Issue
I'm new to asynchronous programming in Python and I'm trying to program an example coroutine that awaits until an arbitrary condition is met. Is this a proper way to implement it?
async def foo():
print('foo') # this is executed before we start checking the condition
while not condition:
await asyncio.sleep(1)
print('bar') # this is executed after the condition is met
Solution
As @L3viathan mentioned, asyncio.Event can be used to achive it.
Here's little example:
import asyncio
async def foo(event):
while True:
print('foo')
await event.wait()
print('bar')
async def main():
event = asyncio.Event()
asyncio.create_task(foo(event))
for i in range(5):
await asyncio.sleep(i)
event.set()
event.clear()
asyncio.run(main())
Answered By - Mikhail Gerasimov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.