I am new to Firestore / Document DB / NoSQL, so please be patient with me on this.
I have something like below where a document is created in the "Users" collection when user sign in for the first time
class FirestoreService{
private val db = Firebase.firestore
private var userExists:Int = 0
private var documentRef = ""
fun addUser(user: User) {
// check if the user exists
db.collection("Users")
.whereEqualTo("Email", user.email).get()
.addOnSuccessListener { documents ->
// async, so following variables will not be initialized when
// synchronous code is being called
for (document in documents) {
documentRef = document.id
userExists = if(docRef!=null) 1 else 0
}
}
.addOnFailureListener { e ->
Log.w(TAG, "Error adding User document", e)
}
if (userExists == 0){
val userHashMap = hashMapOf(
"name" to user.name,
"email" to user.email,
"notif" to false
)
db.collection("Users")
.add(userHashMap)
.addOnSuccessListener { documentReference ->
Log.d(TAG, "User document added!")
Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}")
}
.addOnFailureListener { e ->
Log.w(TAG, "Error adding User document", e)
}
}
}
fun updateUser(user:User){
db.collection("Users")
.document(documentRef)
.set({
"notif" to user.settings?.notifOn
})
.addOnSuccessListener { Log.d(TAG, "User DocumentSnapshot successfully updated!") }
.addOnFailureListener { e -> Log.w(TAG, "Error updating User document", e) }
}
}
Inside a fragment
// inside fragment method
val firestoreService = FirestoreService()
firestoreService.addUser(user);
// inside another fragment method
firestoreService.updateUser(user2)
As you can see I am setting variables inside addOnSuccessListener
which is asynchronous so the synchronous if
condition and updateUser
calls do not work as expected (required values may not be assigned to the userExists
, documentRef
when synchrnous code being called). As I know these async behavior is handled using callbacks like mentioned in here. But I am not sure how to make it work in my case with addOnSuccessListener
?