Skip to content

Commit cebfe80

Browse files
authored
Raise error if EventEmitter used with async callback (#312)
1 parent f392454 commit cebfe80

File tree

2 files changed

+16
-9
lines changed

2 files changed

+16
-9
lines changed

livekit-rtc/livekit/rtc/event_emitter.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import inspect
2+
import asyncio
23
from typing import Callable, Dict, Set, Optional, Generic, TypeVar
34

45
from .log import logger
@@ -156,6 +157,11 @@ def greet(name):
156157
```
157158
"""
158159
if callback is not None:
160+
if asyncio.iscoroutinefunction(callback):
161+
raise ValueError(
162+
"Cannot register an async callback with `.on()`. Use `asyncio.create_task` within your synchronous callback instead."
163+
)
164+
159165
if event not in self._events:
160166
self._events[event] = set()
161167
self._events[event].add(callback)

livekit-rtc/tests/test_emitter.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -60,26 +60,27 @@ def on_whatever(first, second, third):
6060
emitter.emit("whatever", 1, 2, 3)
6161
emitter.emit("whatever", 1, 2, 3, 4, 5) # only 3 arguments will be passed
6262

63-
assert len(calls) == 2
64-
assert calls[0] == (1, 2, 3)
65-
assert calls[1] == (1, 2, 3)
66-
67-
calls = []
63+
assert calls == [(1, 2, 3), (1, 2, 3)]
6864

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

72-
assert len(calls) == 0
68+
69+
def test_varargs():
70+
EventTypes = Literal["whatever"]
71+
72+
emitter = EventEmitter[EventTypes]()
73+
74+
calls = []
7375

7476
@emitter.on("whatever")
7577
def on_whatever_varargs(*args):
7678
calls.append(args)
7779

7880
emitter.emit("whatever", 1, 2, 3, 4, 5)
81+
emitter.emit("whatever", 1, 2)
7982

80-
assert len(calls) == 2
81-
assert calls[0] == (1, 2, 3)
82-
assert calls[1] == (1, 2, 3, 4, 5)
83+
assert calls == [(1, 2, 3, 4, 5), (1, 2)]
8384

8485

8586
def test_throw():

0 commit comments

Comments
 (0)