diff --git a/.changeset/fast-pots-fold.md b/.changeset/fast-pots-fold.md new file mode 100644 index 0000000000..e81bd10df4 --- /dev/null +++ b/.changeset/fast-pots-fold.md @@ -0,0 +1,5 @@ +--- +"livekit-client": patch +--- + +fix: improve ordering of resolving waitForBufferStatus calls diff --git a/src/room/RTCEngine.ts b/src/room/RTCEngine.ts index 69f9023552..aca0209cef 100644 --- a/src/room/RTCEngine.ts +++ b/src/room/RTCEngine.ts @@ -1557,18 +1557,31 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit } }; - waitForBufferStatusLow(kind: DataChannelKind): TypedPromise { - return new TypedPromise(async (resolve, reject) => { + async waitForBufferStatusLow(kind: DataChannelKind) { + return new TypedPromise(async (resolve, reject) => { + if (this.isClosed) { + reject(new UnexpectedConnectionState('engine closed')); + } if (this.isBufferStatusLow(kind)) { resolve(); } else { const onClosing = () => reject(new UnexpectedConnectionState('engine closed')); this.once(EngineEvent.Closing, onClosing); - while (!this.dcBufferStatus.get(kind)) { - await sleep(10); + const dc = this.dataChannelForKind(kind); + if (!dc) { + reject(new UnexpectedConnectionState(`DataChannel not found, kind: ${kind}`)); + return; } - this.off(EngineEvent.Closing, onClosing); - resolve(); + dc.addEventListener( + 'bufferedamountlow', + () => { + this.off(EngineEvent.Closing, onClosing); + resolve(); + }, + { + once: true, + }, + ); } }); }