@@ -45,6 +45,9 @@ def __init__(
4545
4646 self ._cleaner : asyncio .Task | None = None
4747
48+ # the current `self._maybe_save_document()` task.
49+ self ._maybe_save_task : asyncio .Task | None = None
50+
4851 # the task currently saving to disk via FileLoader, if any.
4952 self ._save_task : asyncio .Task | None = None
5053
@@ -219,7 +222,17 @@ def _on_document_change(self, target: str, event: Any) -> None:
219222 document. This tasks are debounced (60 seconds by default) so we
220223 need to cancel previous tasks before creating a new one.
221224 """
222- asyncio .create_task (self ._maybe_save_document ())
225+ if self ._maybe_save_task and not self ._maybe_save_task .done ():
226+ # only one `self._maybe_save_task` needs to be running.
227+ # if this method is called after the save delay, then we need to set
228+ # `self._should_resave` to `True` to reschedule
229+ # `self._maybe_save_document()` on the event loop after the current
230+ # `self._maybe_save_task` completes.
231+ if not self ._waiting_to_save :
232+ self ._should_resave = True
233+ return
234+
235+ self ._maybe_save_task = asyncio .create_task (self ._maybe_save_document ())
223236
224237 async def _maybe_save_document (self ) -> None :
225238 """
@@ -234,19 +247,6 @@ async def _maybe_save_document(self) -> None:
234247 # TODO: fix this; if _save_delay is unset, then this never writes to disk
235248 return
236249
237- if self ._waiting_to_save :
238- # if a previously spawned `self._maybe_save_document()` task is
239- # waiting to save, then that task will save the Ydoc within
240- # `self._save_delay` seconds. therefore we can return early.
241- return
242-
243- if self ._save_task and not self ._save_task .done ():
244- # if we are currently saving, then set the `_should_resave`
245- # flag. this indicates to the currently running `self._save_task`
246- # that it should re-call this method after it completes.
247- self ._should_resave = True
248- return
249-
250250 # save after `self._save_delay` seconds of inactivity
251251 self ._waiting_to_save = True
252252 await asyncio .sleep (self ._save_delay )
@@ -271,7 +271,7 @@ async def _maybe_save_document(self) -> None:
271271
272272 if self ._should_resave :
273273 self ._should_resave = False
274- asyncio .create_task (self ._maybe_save_document ())
274+ self . _maybe_save_task = asyncio .create_task (self ._maybe_save_document ())
275275
276276 except asyncio .CancelledError :
277277 return
0 commit comments