In Firebase and Kotlin, in case of no network connection is there an easy way to handle endless network request looping?

Viewed 67

In the case of network connectivity loss, the following code just loops endlessly and keeps making API calls. Is there a way to cancel with a timeout (for example, 5000 ms) using Firebase API? Or would I have to make my own Coroutine to handle this?

fun updateUserFieldInDB(
            collectionPath: String,
            strArr: ArrayList<String>,
            onSuccess: (() -> Unit),
            onFail: (() -> Unit)
        ) {

            val fbUser = Firebase.auth.currentUser

            if (fbUser == null) {
                Log.i(TAG, "user is null....")
                return
            }

            val db = Firebase.firestore

            when (strArr.size) {
                2 -> {
                    db.collection(collectionPath).document(fbUser.uid).update(strArr[0], strArr[1])
                        .addOnSuccessListener {
                            onSuccess()
                        }
                        .addOnFailureListener {
                                onFail()
                        }

                }
            }
        }
1 Answers

The onSuccess ad onFail completion handlers for Firestore only fire once the write operation has been committed or rejected on the server. You should only use them if you're interested in detecting that situation, in which case the looping is to be expected.

If you only care whether the write operation was recorded by the Firestore client (in its local cache), the best way to detect that is when the update(strArr[0], strArr[1]) call completes.

So pretty much: when the next line of code executes, the write has been recorded locally; when the completion listeners fire, the write has been handled on the server.

Related