1
1
import { log , setupLiveKitRoom } from '@livekit/components-core' ;
2
2
import type { DisconnectReason } from 'livekit-client' ;
3
- import { Room , MediaDeviceFailure , RoomEvent } from 'livekit-client' ;
3
+ import { Room , MediaDeviceFailure , RoomEvent , Mutex } from 'livekit-client' ;
4
4
import * as React from 'react' ;
5
5
import type { HTMLAttributes } from 'react' ;
6
6
@@ -126,6 +126,8 @@ export function useLiveKitRoom<T extends HTMLElement>(
126
126
onDisconnected ,
127
127
] ) ;
128
128
129
+ const connectDisconnectLock = React . useMemo ( ( ) => new Mutex ( ) , [ ] ) ;
130
+
129
131
React . useEffect ( ( ) => {
130
132
if ( ! room ) return ;
131
133
@@ -155,20 +157,30 @@ export function useLiveKitRoom<T extends HTMLElement>(
155
157
return ;
156
158
}
157
159
158
- const connectionPromise = room . connect ( serverUrl , token , connectOptions ) ;
159
- ( connectionSideEffect ? Promise . all ( [
160
- connectionPromise ,
161
- connectionSideEffect ,
162
- ] ) : connectionPromise ) . catch ( ( e ) => {
163
- log . warn ( e ) ;
164
- if ( shouldConnect . current === true ) {
165
- onError ?.( e as Error ) ;
160
+ connectDisconnectLock . lock ( ) . then ( async ( unlock ) => {
161
+ try {
162
+ const connectionPromise = room . connect ( serverUrl , token , connectOptions ) ;
163
+ if ( connectionSideEffect ) {
164
+ await Promise . all ( [ connectionPromise , connectionSideEffect ] ) ;
165
+ } else {
166
+ await connectionPromise ;
167
+ }
168
+ } catch ( e ) {
169
+ log . warn ( e ) ;
170
+ if ( shouldConnect . current === true ) {
171
+ onError ?.( e as Error ) ;
172
+ }
173
+ } finally {
174
+ unlock ( ) ;
166
175
}
167
176
} ) ;
168
177
} else {
169
178
log . debug ( 'disconnecting because connect is false' ) ;
170
179
shouldConnect . current = false ;
171
- room . disconnect ( ) ;
180
+ connectDisconnectLock . lock ( ) . then ( async ( unlock ) => {
181
+ await room . disconnect ( ) ;
182
+ unlock ( ) ;
183
+ } ) ;
172
184
}
173
185
} , [
174
186
connect ,
@@ -185,7 +197,10 @@ export function useLiveKitRoom<T extends HTMLElement>(
185
197
if ( ! room ) return ;
186
198
return ( ) => {
187
199
log . info ( 'disconnecting on onmount' ) ;
188
- room . disconnect ( ) ;
200
+ connectDisconnectLock . lock ( ) . then ( async ( unlock ) => {
201
+ await room . disconnect ( ) ;
202
+ unlock ( ) ;
203
+ } ) ;
189
204
} ;
190
205
} , [ room ] ) ;
191
206
0 commit comments