3

I have this code

val collectionDb = db.collection(collection)
                .add(user4)
                .addOnSuccessListener { documentReference ->
                    Log.d("SUCCESS", "DocumentSnapshot added with ID: ${documentReference.id}")
                    println(documentReference.id)
                }
                .addOnFailureListener { e ->
                    Log.w("FAIL", "Error adding document", e)
                }

                //here wait

                println("more code")

    }

The output is first more code and later the DocumentReference.id

But I want that on //here wait the script pause until there is a success or a fail.

I'm new so it would be very nice when you can help me out.

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
MoDi
  • 66
  • 7
  • 1
    You might also take a look at this [answer](https://stackoverflow.com/questions/48499310/how-to-return-a-documentsnapshot-as-a-result-of-a-method/48500679#48500679). – Alex Mamo Apr 07 '21 at 06:23

2 Answers2

2

When you want to execute script after success or failure just create a method and call it from success or failure callback as below.Please check if below is useful.

 val collectionDb = db.collection(collection)
            .add(user4)
            .addOnSuccessListener { documentReference ->
                Log.d("SUCCESS", "DocumentSnapshot added with ID: ${documentReference.id}")
                println(documentReference.id)
                doRequiredOperation("Success")
            }
            .addOnFailureListener { e ->
                Log.w("FAIL", "Error adding document", e)
                doRequiredOperation("failuire")
            }


fun doRequiredOperation(msg:String){
    if(msg.equals("Success"){
        println("more code"). //It will execute after success callback 
    }
}
Tarun Anchala
  • 2,232
  • 16
  • 15
1

But I want that on //here wait the script pause until there is a success or a fail.

That would be impossible. That's the point of an asynchronous operation - it will complete, whether it succeeds or fails, at a later point in time and when that time will be, we can't really be sure. I have a Q&A here if you want more information on how to handle these types of functions: Why does my function that calls an API return an empty or null value?

but your best bet would be to add all the relevant code inside your addOnSuccessListener listener, because this is where you know that the request has completed and it succeeded

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51