diff --git a/realtime/channel.py b/realtime/channel.py index e4ac908..c45a0af 100644 --- a/realtime/channel.py +++ b/realtime/channel.py @@ -46,6 +46,13 @@ def join(self) -> Channel: loop.run_until_complete(self._join()) return self + async def join_async(self) -> None: + """ + Wrapper for async def _join(). + :return: None + """ + await self._join() + async def _join(self) -> None: """ Coroutine that attempts to join Phoenix Realtime server via a certain topic diff --git a/realtime/connection.py b/realtime/connection.py index 5546aac..01213a0 100644 --- a/realtime/connection.py +++ b/realtime/connection.py @@ -65,6 +65,18 @@ def listen(self) -> None: loop = asyncio.get_event_loop() # TODO: replace with get_running_loop loop.run_until_complete(asyncio.gather(self._listen(), self._keep_alive())) + async def listen_async(self) -> None: + """ + Wrapper for async def _listen() and async def _keep_alive() to expose an async interface. + :return: None + """ + # @ensure_connection is definitely nicer, but I don't know if it is also + # working for asynchronous functions. + if not self.connected: + raise NotConnectedError(self.listen_async.__name__) + + await asyncio.gather(self._listen(), self._keep_alive()) + async def _listen(self) -> None: """ An infinite loop that keeps listening. @@ -103,6 +115,12 @@ def connect(self) -> None: loop.run_until_complete(self._connect()) self.connected = True + async def connect_async(self) -> None: + """ + Wrapper for async def _connect() to expose a async interface. + """ + await self._connect() + async def _connect(self) -> None: ws_connection = await websockets.connect(self.url) @@ -156,4 +174,4 @@ def summary(self) -> None: """ for topic, chans in self.channels.items(): for chan in chans: - print(f"Topic: {topic} | Events: {[e for e, _ in chan.callbacks]}]") + print(f"Topic: {topic} | Events: {[e for e, _ in chan.listeners]}")