Skip to content

Commit efed63c

Browse files
committed
Allow set connect retry to connect function
1 parent c6646c3 commit efed63c

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

livekit-android-sdk/src/main/java/io/livekit/android/LiveKit.kt

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import io.livekit.android.room.Room
2626
import io.livekit.android.room.RoomListener
2727
import io.livekit.android.util.LKLog
2828
import io.livekit.android.util.LoggingLevel
29+
import io.livekit.android.util.executeSuspendWithRetry
2930
import timber.log.Timber
3031

3132
class LiveKit {
@@ -114,6 +115,7 @@ class LiveKit {
114115
* Connect to a LiveKit room
115116
* @param url URL to LiveKit server (i.e. ws://mylivekitdeploy.io)
116117
* @param listener Listener to Room events. LiveKit interactions take place with these callbacks
118+
* @param maxConnectRetry Int to set max connect retry.
117119
*/
118120
@Deprecated("Use LiveKit.create and Room.connect instead. This is limited to max protocol 7.")
119121
suspend fun connect(
@@ -124,6 +126,7 @@ class LiveKit {
124126
roomOptions: RoomOptions = RoomOptions(),
125127
listener: RoomListener? = null,
126128
overrides: LiveKitOverrides = LiveKitOverrides(),
129+
maxConnectRetry: Int = 0
127130
): Room {
128131
val room = create(appContext, roomOptions, overrides)
129132

@@ -132,7 +135,10 @@ class LiveKit {
132135
val protocolVersion = maxOf(options.protocolVersion, ProtocolVersion.v7)
133136
val connectOptions = options.copy(protocolVersion = protocolVersion)
134137

135-
room.connect(url, token, connectOptions)
138+
executeSuspendWithRetry(maxConnectRetry){
139+
room.connect(url, token, connectOptions)
140+
}
141+
136142
return room
137143
}
138144
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package io.livekit.android.util
2+
3+
import kotlinx.coroutines.delay
4+
5+
suspend fun <T>executeSuspendWithRetry(maxRetries: Int, suspendFunction: suspend () -> T): T {
6+
var currentAttempt = 0
7+
var lastException: Exception? = null
8+
9+
while (currentAttempt <= maxRetries) {
10+
try {
11+
return suspendFunction()
12+
} catch (e: Exception) {
13+
LKLog.i {"connection number $currentAttempt failed with $e"}
14+
// Store the last exception for error logging
15+
lastException = e
16+
currentAttempt++
17+
18+
// Delay before retrying
19+
delay(1_000L * currentAttempt)
20+
}
21+
}
22+
23+
throw lastException ?: RuntimeException("Max retries exceeded")
24+
}

0 commit comments

Comments
 (0)