Skip to content

Commit

Permalink
Added documentation to the sync decorator method
Browse files Browse the repository at this point in the history
  • Loading branch information
sacOO7 committed Sep 29, 2023
1 parent c6d99a4 commit 33c940b
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions ably/decorator/sync.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import asyncio
import functools
import threading
from asyncio import events

_loop = None
_thread = None
_loop: events = None
_thread: threading = None


def get_custom_event_loop():
def get_custom_event_loop() -> events:
global _loop, _thread
if _thread is None:
if _loop is None:
Expand All @@ -31,13 +32,21 @@ def optional_sync(fn):
def wrapper(*args, **kwargs):
caller_eventloop = None
try:
caller_eventloop = asyncio.get_running_loop()
caller_eventloop: events = asyncio.get_running_loop()
except:
pass
ably_eventloop = get_custom_event_loop()
ably_eventloop: events = get_custom_event_loop()

# Handle calls from ably_eventloop on the same loop, return awaitable
if caller_eventloop is not None and caller_eventloop == ably_eventloop:
return ably_eventloop.create_task(fn(*args, **kwargs))

# Post external calls on ably_eventloop, return awaitable on calling eventloop
future = asyncio.run_coroutine_threadsafe(fn(*args, **kwargs), ably_eventloop)
if caller_eventloop is not None and caller_eventloop.is_running():
return asyncio.wrap_future(future)

# If called from regular function instead of coroutine, block till result is available
return future.result()

return wrapper

0 comments on commit 33c940b

Please sign in to comment.