diff --git a/ably/decorator/sync.py b/ably/decorator/sync.py index 16095585..f3577072 100644 --- a/ably/decorator/sync.py +++ b/ably/decorator/sync.py @@ -37,3 +37,28 @@ def wrapper(*args, **kwargs): return res return wrapper + + +def close_app_eventloop(fn): + import asyncio + + @functools.wraps(fn) + def wrapper(*args, **kwargs): + + caller_eventloop = None + try: + caller_eventloop: events = asyncio.get_running_loop() + except Exception: + pass + + app_eventloop: events = AppEventLoop.current() + if caller_eventloop is not None: + app_eventloop.close() + return caller_eventloop.create_task(fn(*args, **kwargs)) + else: + future = asyncio.run_coroutine_threadsafe(fn(*args, **kwargs), app_eventloop.loop) + result = future.result() + app_eventloop.close() + return result + + return wrapper diff --git a/ably/rest/rest.py b/ably/rest/rest.py index 3c8cb984..1c636147 100644 --- a/ably/rest/rest.py +++ b/ably/rest/rest.py @@ -2,7 +2,7 @@ from typing import Optional from urllib.parse import urlencode -from ably.decorator.sync import optional_sync +from ably.decorator.sync import optional_sync, close_app_eventloop from ably.executer.eventloop import AppEventLoop from ably.http.http import Http from ably.http.paginatedresult import PaginatedResult, HttpPaginatedResponse @@ -152,12 +152,8 @@ async def __aexit__(self, *excinfo): await self.close() def __exit__(self, *excinfo): - self.close_sync() + self.close() + @close_app_eventloop async def close(self): await self.http.close() - AppEventLoop.current().close() - - def close_sync(self): - self.http.close() - AppEventLoop.current().close()