NativeScript / mlkit

Apache License 2.0
24 stars 9 forks source link

IOS & Android: OnDetection method is called from background thread #20

Closed cjohn001 closed 2 years ago

cjohn001 commented 2 years ago

It seems like the (detection)="OnDetection($event)" method from the MLKitView is called from a background thread. When I try to modify something in the ui within the callback function the UI breaks. On Android it breaks silently. On iOS I am observing the following error message:

This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread. This can lead to engine corruption and weird crashes.
Stack:(
0   CoreAutoLayout                      0x0000000199b58710 34226C3D-B469-32D6-A7B6-82E027859D41 + 22288
1   CoreAutoLayout                      0x0000000199b5b5c4 34226C3D-B469-32D6-A7B6-82E027859D41 + 34244
2   UIKitCore                           0x00000001837cd26c 8388EB03-002B-3B35-A78A-6A022894292E + 1897068
3   UIKitCore                           0x00000001839bb804 8388EB03-002B-3B35-A78A-6A022894292E + 3921924
4   UIKitCore                           0x00000001837dddbc 8388EB03-002B-3B35-A78A-6A022894292E + 1965500
5   UIKitCore                           0x000000018386cfd8 8388EB03-002B-3B35-A78A-6A022894292E + 2551768
6   UIKitCore                           0x00000001837898d4 8388EB03-002B-3B35-A78A-6A022894292E + 1620180
7   UIKitCore                           0x0000000183a94c3c 8388EB03-002B-3B35-A78A-6A022894292E + 4811836
8   UIKitCore                           0x00000001837c1528 8388EB03-002B-3B35-A78A-6A022894292E + 1848616
9   UIKitCore                           0x00000001838
CONSOLE ERROR: ERROR Error: Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread.

It would be great if you could dispatch back to the main/ui thread before calling the callback function. Alternatively, please show in the demo application how I could execute code in the main tread in case I need to do it myself. What I need to do in the callback: Retrieve first barcode, pause scanner, navigate to a different page or show something in the ui of the same page. I have unfortunately not found any documentation in NS which explains threading topics like this. However, I assume what everybody would like to have is, to have the callback function executed in the main/ui thread.

triniwiz commented 2 years ago

Good catch I could of swore I dispatched it to the main :) will patch, as for dispatching to the main there is a util in nativescript core module that can be used for this

import { Utils } from '@nativescript/core';
Utils.dispatchToMainThread(()=>{})
cjohn001 commented 2 years ago

@triniwiz : Thank you very much for the hint, I would have never found this function :)