Skip to content

Commit

Permalink
Allow set connect retry to connect function
Browse files Browse the repository at this point in the history
  • Loading branch information
mohsen2986 committed Jan 7, 2024
1 parent 7a45b21 commit cf49991
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import io.livekit.android.room.Room
import io.livekit.android.room.RoomListener
import io.livekit.android.util.LKLog
import io.livekit.android.util.LoggingLevel
import io.livekit.android.util.executeSuspendWithRetry
import timber.log.Timber

class LiveKit {
Expand Down Expand Up @@ -59,19 +60,23 @@ class LiveKit {
* Connect to a LiveKit room
* @param url URL to LiveKit server (i.e. ws://mylivekitdeploy.io)
* @param listener Listener to Room events. LiveKit interactions take place with these callbacks
* @param maxConnectRetry Int to set max connect retry.
*/
suspend fun connect(
appContext: Context,
url: String,
token: String,
options: ConnectOptions = ConnectOptions(),
roomOptions: RoomOptions = RoomOptions(),
listener: RoomListener? = null
listener: RoomListener? = null ,
maxConnectRetry: Int = 0
): Room {
val room = create(appContext, roomOptions)

room.listener = listener
room.connect(url, token, options)
executeSuspendWithRetry(maxConnectRetry){
room.connect(url, token, options)
}
return room
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package io.livekit.android.util

import kotlinx.coroutines.delay

suspend fun <T>executeSuspendWithRetry(maxRetries: Int, suspendFunction: suspend () -> T): T {
var currentAttempt = 0
var lastException: Exception? = null

while (currentAttempt <= maxRetries) {
try {
return suspendFunction()
} catch (e: Exception) {
LKLog.i {"connection number $currentAttempt failed with $e"}
// Store the last exception for error logging
lastException = e
currentAttempt++

// Delay before retrying
delay(1_000L * currentAttempt)
}
}

throw lastException ?: RuntimeException("Max retries exceeded")
}

0 comments on commit cf49991

Please sign in to comment.