Skip to content

Commit

Permalink
fix(NetworkMonitor): add async completion() method
Browse files Browse the repository at this point in the history
  • Loading branch information
jourdain committed Sep 16, 2024
1 parent 64817de commit 62e4c68
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions python/src/wslink/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,17 +67,28 @@ def onClose(self, client_id):


class NetworkMonitor:
"""
Provide context manager for increase/decrease pending request
either synchronously or asynchronously.
The Asynchronous version also await completion.
"""

def __init__(self):

self.pending = 0
self.event = asyncio.Event()

def network_call_completed(self):
"""Trigger completion event"""
self.event.set()

def on_enter(self, *args, **kwargs):
"""Increase pending request"""
self.pending += 1

def on_exit(self, *args, **kwargs):
"""Decrease pending request and trigger completion event if we reach 0 pending request"""
self.pending -= 1
if self.pending == 0 and not self.event.is_set():
self.event.set()
Expand All @@ -97,6 +108,10 @@ async def __aenter__(self):

async def __aexit__(self, exc_t, exc_v, exc_tb):
self.on_exit()
await self.completion()

async def completion(self):
"""Await completion of any pending network request"""
while self.pending:
self.event.clear()
await self.event.wait()
Expand Down

0 comments on commit 62e4c68

Please sign in to comment.