Skip to content

Commit 3aa07e4

Browse files
committed
fix: prevent duplicate or lost events in subscribeAndReplayHistory
1 parent d8fa7fc commit 3aa07e4

1 file changed

Lines changed: 11 additions & 3 deletions

File tree

src/hx/concurrent/event/EventDispatcherWithHistory.hx

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,20 @@ class EventDispatcherWithHistory<EVENT> implements EventDispatcher<EVENT> {
3737
if (listener == null)
3838
throw "[listener] must not be null";
3939

40-
if (_wrapped.subscribe(listener)) {
41-
for (event in _eventHistory)
40+
// Take a snapshot and subscribe while holding the history lock to avoid
41+
// losing events that might be fired between snapshot and subscription.
42+
var history:Array<EVENT>;
43+
var added = false;
44+
_eventHistoryLock.execute(() -> {
45+
history = _eventHistory.copy();
46+
added = _wrapped.subscribe(listener);
47+
});
48+
49+
if (added) {
50+
for (event in history)
4251
listener(event);
4352
return true;
4453
}
45-
4654
return false;
4755
}
4856

0 commit comments

Comments
 (0)