How to structure code when there are too many events android

Mangesh :

I am new to Firestore and learning Android. The problem I am facing is about structuring the code. Following is my use case:

  1. The user wants to add a new note, inputs note's title
  2. I want to check if any other note with the same title exists
  3. 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.

Alex Mamo :

Therefore, I need to add my exists logic in OnSuccessListener.

Yes, when onSuccess() fires, it means that you are 100% sure that the operation of getting the data from the database is 100% successful and you can use that data as needed. You always need to wait for the data.

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.

Yes, that the way asynchronous programming works.

Also, from where to return the value true/false to original caller fnValidate?

There is no way you can return the data (fnValidate) as a result of a method. For a working solution, please see my answer from the following post:

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=401253&siteId=1