1

I have a big problem with CountDownLatch. I'm working on app which uses Firestore as database. I've created a file for managing the database, and I want to wait for for example writeSomethingToDb() function to complete. I found this example how to use CountDownLatch https://www.javaquery.com/2016/09/how-to-save-data-in-firebase.html , it's realtime database, but it have similar functionality I guess. I wrote my code, trying to do save something by this function, but app just hangs. It looks like it never goes to OnComplete, but without CountDownLatch, the data is added to the database correctly.

public void addSomethingToDb(FirestoreCollections collections, Object data) {
    CountDownLatch countDownLatch = new CountDownLatch(1);
     db.collection(collections.getName()).add(data).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
         @Override
         public void onComplete(@NonNull Task<DocumentReference> task) {
             if(task.isSuccessful()){
                 Toast.makeText(context, String.valueOf(countDownLatch.getCount()), Toast.LENGTH_SHORT).show();
                 countDownLatch.countDown();
                 Toast.makeText(context, String.valueOf(countDownLatch.getCount()), Toast.LENGTH_SHORT).show();

             }else{
                 Toast.makeText(context, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
             }
         }
     });
     try{
         countDownLatch.await();
     } catch (InterruptedException e) {
         e.printStackTrace();
     }

}
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Flubbershy
  • 13
  • 3
  • Programming like this is almost certainly **not** what you want to do on Android, unless you're certain you need to block a thread. Blocking threads is normally very bad. – Doug Stevenson Jul 23 '18 at 21:47
  • Check **[this](https://stackoverflow.com/questions/48499310/firestore-object-with-inner-object/48500679)** out. – Alex Mamo Jul 24 '18 at 08:32
  • I think @AlexMamo this is the best solution, thank you ! – Flubbershy Jul 24 '18 at 17:20

1 Answers1

-1

Basically, you're trying to add data to database synchronously using an API that's asynchronous. That's not a good idea because you'll end up having your thread blocked. So you should handle the APIs asynchronously as intended. As in my comment, to solve that, I recommend you see my anwser from this post and for a better understanding, you can also take a look at this video .

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193