0

I have this code to check if a user already exists in firestore

1  private fun usernameRepeated(db: FirebaseFirestore, username: String): Boolean {
2      var res = false
3      db.collection("User").whereEqualTo("username", username).get().addOnSuccessListener { task ->
4          res = task.documents.isNotEmpty()
5      }
6      return res
7  }

But it doesn't work. I have debugged the code putting breakpoints on lines 2, 4 and 6. When the debugger comes to this point, it runs lines 2 and 3 correctly, but skips line 4 and goes to line 6 directly, always returning "false". Long after running the rest of the lines of the function where I call this one, it comes back and runs only line 4, when it is already too late.

Chema
  • 15
  • 4

1 Answers1

1

It does not skip that section, but executes asynchronously only when result from database is retrieved.

What is happening is that the method returns False and only then the callback is executed.

You should instead of returning result, pass a callback

private fun usernameRepeated(db: FirebaseFirestore, username: String, onSuccess: (result: Task) => Boolean): Boolean {
 db.collection("User").whereEqualTo("username", username).get().addOnSuccessListener { onSuccess }
}

Or you can block the request with coroutine, RxJava or other API

Heisenberg
  • 3,153
  • 3
  • 27
  • 55