Skip to content

Commit

Permalink
Raise error if EventEmitter used with async callback (#312)
Browse files Browse the repository at this point in the history
  • Loading branch information
bcherry authored Nov 22, 2024
1 parent f392454 commit cebfe80
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
6 changes: 6 additions & 0 deletions livekit-rtc/livekit/rtc/event_emitter.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import inspect
import asyncio
from typing import Callable, Dict, Set, Optional, Generic, TypeVar

from .log import logger
Expand Down Expand Up @@ -156,6 +157,11 @@ def greet(name):
```
"""
if callback is not None:
if asyncio.iscoroutinefunction(callback):
raise ValueError(
"Cannot register an async callback with `.on()`. Use `asyncio.create_task` within your synchronous callback instead."
)

if event not in self._events:
self._events[event] = set()
self._events[event].add(callback)
Expand Down
19 changes: 10 additions & 9 deletions livekit-rtc/tests/test_emitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,26 +60,27 @@ def on_whatever(first, second, third):
emitter.emit("whatever", 1, 2, 3)
emitter.emit("whatever", 1, 2, 3, 4, 5) # only 3 arguments will be passed

assert len(calls) == 2
assert calls[0] == (1, 2, 3)
assert calls[1] == (1, 2, 3)

calls = []
assert calls == [(1, 2, 3), (1, 2, 3)]

with pytest.raises(TypeError):
emitter.emit("whatever", 1, 2)

assert len(calls) == 0

def test_varargs():
EventTypes = Literal["whatever"]

emitter = EventEmitter[EventTypes]()

calls = []

@emitter.on("whatever")
def on_whatever_varargs(*args):
calls.append(args)

emitter.emit("whatever", 1, 2, 3, 4, 5)
emitter.emit("whatever", 1, 2)

assert len(calls) == 2
assert calls[0] == (1, 2, 3)
assert calls[1] == (1, 2, 3, 4, 5)
assert calls == [(1, 2, 3, 4, 5), (1, 2)]


def test_throw():
Expand Down

0 comments on commit cebfe80

Please sign in to comment.