Skip to content

Commit

Permalink
Updated decorator function for closing event loop
Browse files Browse the repository at this point in the history
  • Loading branch information
sacOO7 committed Oct 2, 2023
1 parent a99ec13 commit e0ebc68
Showing 1 changed file with 17 additions and 10 deletions.
27 changes: 17 additions & 10 deletions ably/executer/decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,22 +113,29 @@ def close_app_eventloop(fn):
import asyncio

@functools.wraps(fn)
def wrapper(*args, **kwargs):
def wrapper(self, *args, **kwargs):

app_loop = AppEventLoop.get_global()
# Handle result of the given async method, with blocking behaviour
caller_eventloop = None
try:
caller_eventloop: events = asyncio.get_running_loop()
except Exception:
pass

app_eventloop: events = AppEventLoop.get_global()
if caller_eventloop is not None:
app_eventloop.close()
return fn(*args, **kwargs)
else:
future = asyncio.run_coroutine_threadsafe(fn(*args, **kwargs), app_eventloop.loop)
result = future.result()
app_eventloop.close()
return result
# Handle calls from app eventloop on the same loop, return awaitable
if caller_eventloop is not None and caller_eventloop == app_loop.loop:
return fn(self, *args, **kwargs)

# Return awaitable as is!
if not self.sync_enabled:
app_loop.close()
return fn(self, *args, **kwargs)

# Block the caller till result is returned
future = asyncio.run_coroutine_threadsafe(fn(self, *args, **kwargs), app_loop.loop)
result = future.result()
app_loop.close()
return result

return wrapper

0 comments on commit e0ebc68

Please sign in to comment.