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();
}
}