I am new to Firestore and learning Android. The problem I am facing is about structuring the code. Following is my use case:
- The user wants to add a new note, inputs note's title
- I want to check if any other note with the same title exists
- If yes, then don't allow, else create
Earlier it was easy with SQLite. I could just run a query to get data in a list, check the list and act accordingly.
// BEFORE
private boolean fnValidate() {
// some code...
// run Sqlite query and get data in a list or something
// check if exists, return accordingly
}
// NOW
private boolean fnValidate() {
// some code...
notesRef.get().addOnSuccessListener(queryDocumentSnapshots -> {
for (QueryDocumentSnapshot s : queryDocumentSnapshots) {
// add data to list or something
}
// 'exists logic' will go here??
}).addOnFailureListener(e -> {
// show error
});
// I want 'exists logic' here like it was earlier so that I can properly return true/false
}
Now as you can see, this won't work in a sequential manner. It will start the task to get notes and will proceed. Therefore, I need to add my exists logic
in OnSuccessListener
.
Furthermore, in the future, if I have to check for some other value before my exists logic
, I would again have to move exists logic
inside that condition's OnSuccessListener
and so on.
Also, from where to return the value true/false to original caller fnValidate
?
Maybe I'm missing something obvious here, but I am very confused about how the ideal structure should be. Please tell me what are the best practices here.