Skip to content

Commit

Permalink
Added eventloop close decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
sacOO7 committed Sep 29, 2023
1 parent 1af4839 commit 5e05827
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
25 changes: 25 additions & 0 deletions ably/decorator/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
9 changes: 3 additions & 6 deletions ably/rest/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -152,12 +152,9 @@ 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()

0 comments on commit 5e05827

Please sign in to comment.