1
0
Эх сурвалжийг харах

#206 also await handshake in "run once"

Rodja Trappe 2 жил өмнө
parent
commit
f15289cdeb

+ 10 - 3
nicegui/functions/timer.py

@@ -40,18 +40,17 @@ class Timer:
 
     async def _run_once(self) -> None:
         with self.slot:
+            await self._handshake()
             await asyncio.sleep(self.interval)
             await self._invoke_callback()
         self.cleanup()
 
     async def _run_in_loop(self) -> None:
         with self.slot:
+            await self._handshake()
             while True:
                 if self.slot.parent.client.id not in globals.clients:
                     break
-                if not self.slot.parent.client.shared:
-                    # NOTE: we need to wait for the client before state can be further manipulated (see https://github.com/zauberzeug/nicegui/issues/206)
-                    await self.slot.parent.client.handshake()
                 try:
                     start = time.time()
                     if self.active:
@@ -73,6 +72,14 @@ class Timer:
         except Exception:
             traceback.print_exc()
 
+    async def _handshake(self) -> None:
+        '''Wait for the client handshake before the timer callback can can be allowed to manipulate the state.
+        See https://github.com/zauberzeug/nicegui/issues/206 for details.
+        '''
+
+        if not self.slot.parent.client.shared:
+            await self.slot.parent.client.handshake()
+
     def cleanup(self) -> None:
         self.slot = None
         self.callback = None

+ 4 - 2
tests/test_element.py

@@ -1,3 +1,4 @@
+import pytest
 from selenium.webdriver.common.by import By
 
 from nicegui import ui
@@ -128,12 +129,13 @@ def test_remove_and_clear(screen: Screen):
     screen.should_not_contain('Label C')
 
 
-def test_setting_visibility_in_timer(screen: Screen):
+@pytest.mark.parametrize('once', [True, False])
+def test_setting_visibility_in_timer(screen: Screen, once: bool):
     '''reproduction of https://github.com/zauberzeug/nicegui/issues/206'''
     @ui.page('/')
     def page():
         label = ui.label('Some Label')
-        ui.timer(1, lambda: label.set_visibility(False))
+        ui.timer(0.1, lambda: label.set_visibility(False), once=once)
 
     screen.open('/')
     screen.wait(0.5)