So I have integrated Firestore into my android app and I am trying to create a helper function that handles the same repetitious addOnCompleteListener that would be needed for every db query that I need to store data with. I have this helper function working but right now it can only use the one query I pass into it. What I want to know is how should I store/pass to my helper function so that I can do a valid check in a when block? Here is what I am currently doing so you can understand how I am passing information around:
Sample query - db.collection("Users").document(user!!.uid).get()
user is a FirebaseUser
Calling helper function - utils.query(db.collection("Users").document(user!!.uid).get(), auth)
auth is a FirebaseAuth
query function:
fun query(query: Task<DocumentSnapshot>, auth: FirebaseAuth) {
query.addOnCompleteListener { dbTask ->
if (dbTask.isSuccessful) {
val userDoc = dbTask.result
if(userDoc != null) {
if (userDoc.exists()) {
handleQuery(query, auth, true)
} else {
handleQuery(query, auth)
}
}
} else {
Log.d("TAG", "Error: ", dbTask.exception)
}
}
}
handleQuery function:
private fun handleQuery(query: Task<DocumentSnapshot>, auth: FirebaseAuth, exists: Boolean = false) {
val user = auth.currentUser
when (query) {
db.collection("Users").document(user!!.uid).get() -> {
if (exists) Log.i("TAG", "User already exists.")
else {
Log.e("TAG", "User doesn't exist in db. Attempting to add...")
db.collection("Users")
.document(user!!.uid)
.set(hashMapOf(
"uid" to user.uid,
"name" to user.displayName,
"email" to user.email,
"photoURL" to user.photoUrl
))
Log.i("TAG", "User has been added")
}
}
}
}
Any help would be greatly appreciated.