简体   繁体   中英

React-Native NativeModules - Is there an Android/Java callback pattern

In my react-native JS code I'm calling a Native Module and it was blocking the UI thread for about 1.5sec. Running it on a different thread with a Runnable works but I can't capture the returned value that happens inside the Runnable?

@ReactMethod
  public void print(final String printerAddress, final String price, final String description, final String upc, Promise promise) {
    try {
      boolean success = false;

      new Thread(new Runnable() {
        public void run() {
          success = mEpsonPrinter.printLabel(printerAddress, price, description, upc);
        }
      }).start();

        promise.resolve(success);
    } catch (IllegalViewOperationException e) {
        promise.reject(e);
    }
  }

To resolve the immediate problem I placed the promise.resolve(success) call inside the Runnable.run()

try {    
      new Thread(new Runnable() {
        public void run() {
          boolean success = mEpsonPrinter.printLabel(printerAddress, price, description, upc);

        promise.resolve(success);
        }
      }).start();
    } catch (IllegalViewOperationException e) {
        promise.reject(e);
    }

Although I'm still left with questioning a solution for callback pattern with Java.

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