简体   繁体   中英

Best way to wait for two async firebase ml vision method results to use them in a third method

When using firebase ml vision to recognize qr codes and/or text from an image. What is the best way to wait for the async text and barcode detector methods to resolve so I can utilize their results in a third method.

I am aware than I can call an alternative method from each async methods "onsuccess" listener to set a "hasReturned" variable and only proceed once both methods have returned but I am looking for the proper way to do this.

private void firebaseRecognitionFromImage(FirebaseVisionImage image) {

    //detect qr code
    FirebaseVisionBarcodeDetectorOptions options = new FirebaseVisionBarcodeDetectorOptions.Builder().setBarcodeFormats(FirebaseVisionBarcode.FORMAT_ALL_FORMATS).build();
    FirebaseVisionBarcodeDetector qrDetector = FirebaseVision.getInstance().getVisionBarcodeDetector(options);
    qrDetector.detectInImage(image).addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionBarcode>>() {
        @Override
        public void onSuccess(List<FirebaseVisionBarcode> barcodes) { /* RESULT 1 */ }
    });

    //detect text
    FirebaseVisionTextRecognizer textDetector = FirebaseVision.getInstance().getOnDeviceTextRecognizer();
    textDetector.processImage(image).addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
        @Override
        public void onSuccess(FirebaseVisionText texts) { /* RESULT 2 */ }
    });

    //process qr code and text information or lack thereof
    thirdMedthod("RESULT 1", "RESULT 2");
}

You should use one of the variants of Tasks.whenAll() . It will create a new Task object that completes when other tasks complete.

Task<List<FirebaseVisionBarcode>> t1 = qrDetector.detectInImage(image);
Task<FirebaseVisionText> t2 = textDetector.processImage(image);
Tasks.whenAll(t1, t2).addOnSuccessListener(new OnSuccessListener<Void>() {
    // check the results of t1 and t2
});

Learn more about Play Services Tasks API in this blog series .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM