Skip to content

Commit

Permalink
extracted event loop in a separate class
Browse files Browse the repository at this point in the history
  • Loading branch information
sacOO7 committed Sep 29, 2023
1 parent 33c940b commit 8dda5bd
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 18 deletions.
20 changes: 2 additions & 18 deletions ably/decorator/sync.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,7 @@
import asyncio
import functools
import threading
from asyncio import events

_loop: events = None
_thread: threading = None


def get_custom_event_loop() -> events:
global _loop, _thread
if _thread is None:
if _loop is None:
_loop = asyncio.new_event_loop()
if not _loop.is_running():
_thread = threading.Thread(
target=_loop.run_forever,
daemon=True)
_thread.start()
return _loop
from ably.executer.eventloop import AblyEventLoop


def optional_sync(fn):
Expand All @@ -35,7 +19,7 @@ def wrapper(*args, **kwargs):
caller_eventloop: events = asyncio.get_running_loop()
except:
pass
ably_eventloop: events = get_custom_event_loop()
ably_eventloop: events = AblyEventLoop.get_global().loop

# Handle calls from ably_eventloop on the same loop, return awaitable
if caller_eventloop is not None and caller_eventloop == ably_eventloop:
Expand Down
Empty file added ably/executer/__init__.py
Empty file.
34 changes: 34 additions & 0 deletions ably/executer/eventloop.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import asyncio
import threading
from asyncio import events
from threading import Thread


class AblyEventLoop:
loop: events
thread: Thread

__global_event_loop: 'AblyEventLoop' = None

@staticmethod
def get_global() -> 'AblyEventLoop':
if AblyEventLoop.__global_event_loop is None:
AblyEventLoop.__global_event_loop = AblyEventLoop()
AblyEventLoop.__global_event_loop._create_if_not_exist()
return AblyEventLoop.__global_event_loop

def _create_if_not_exist(self):
if self.loop is None:
self.loop = asyncio.new_event_loop()
if not self.loop.is_running():
self.thread = threading.Thread(
target=self.loop.run_forever,
daemon=True)
self.thread.start()

def close(self) -> events:
self.loop.stop()
self.loop.close()
self.loop = None
self.thread = None

0 comments on commit 8dda5bd

Please sign in to comment.