Skip to content

Commit a159c15

Browse files
committed
Python: Fix event loop terminating too early when the main coro finishes
1 parent 797f8f6 commit a159c15

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

api/python/slint/slint/__init__.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -465,9 +465,9 @@ async def run_inner() -> None:
465465
global quit_event
466466
loop = typing.cast(SlintEventLoop, asyncio.get_event_loop())
467467

468-
tasks: typing.List[asyncio.Task[typing.Any]] = [
469-
asyncio.ensure_future(quit_event.wait(), loop=loop)
470-
]
468+
quit_task = asyncio.ensure_future(quit_event.wait(), loop=loop)
469+
470+
tasks: typing.List[asyncio.Task[typing.Any]] = [quit_task]
471471

472472
main_task = None
473473
if main_coro:
@@ -478,6 +478,8 @@ async def run_inner() -> None:
478478

479479
if main_task is not None and main_task in done:
480480
main_task.result() # propagate exception if thrown
481+
if quit_task in pending:
482+
await quit_event.wait()
481483

482484
global quit_event
483485
quit_event = asyncio.Event()

api/python/slint/tests/test_async.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import pytest
1313
import sys
1414
import platform
15+
from datetime import timedelta
1516

1617

1718
def test_async_basic() -> None:
@@ -181,6 +182,23 @@ async def never_quit() -> None:
181182
pytest.fail("Should not throw a run-time error")
182183

183184

185+
def test_loop_continues_when_main_coro_finished() -> None:
186+
async def quit_later(quit_event: asyncio.Event) -> None:
187+
await quit_event.wait()
188+
slint.quit_event_loop()
189+
190+
async def simple(quit_event: asyncio.Event) -> None:
191+
loop = asyncio.get_event_loop()
192+
loop.create_task(quit_later(quit_event))
193+
194+
quit_event = asyncio.Event()
195+
slint.Timer.single_shot(
196+
duration=timedelta(milliseconds=100), callback=lambda: quit_event.set()
197+
)
198+
slint.run_event_loop(simple(quit_event))
199+
assert quit_event.is_set()
200+
201+
184202
@pytest.mark.skipif(platform.system() == "Windows", reason="pipes aren't supported yet")
185203
def test_subprocess() -> None:
186204
async def launch_process(exception_check: typing.List[Exception]) -> None:

0 commit comments

Comments
 (0)