Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - Module Lifecycle - Dispose resources on "Reload"

I am using a react native module (https://github.com/rusel1989/react-native-bluetooth-serial) for Bluetooth communication with an Arduino.

Eveything works just fine. But when I press "Reload" or the application reloads due to Live Reload being enabled, the onDestroy method of the module is not called. Because of that, the sockets (and streams) are no correctly disposed.

When the reload is finished, I can no longer open a bluetooth socket. It requires me to disable and enable bluetooth, or to restart the application.

Is there ant callback or method I could implement that would correctly dispose these sockets when I reload my application?

like image 275
Walter Macambira Avatar asked Dec 05 '16 14:12

Walter Macambira


2 Answers

Ok after spending time in react-native code I found the answer to this:

On iOS:

You'll have to implement a method called invalidate in your RCTBridgeModule implementation:

That will run whenever the context is destroyed (the app is reloaded) and it will look like this:

- (void)invalidate
{
    // disconnect bluetooth here
}

Here's an example of how I did it on iOS.

On Android:

you'll have to implement the onCatalystInstanceDestroy method inside your ReactContextBaseJavaModule and it will look like this:

@Override
public void onCatalystInstanceDestroy() {
    // disconnect bluetooth here
}

Here's an example of how I did it on Android.

like image 141
SudoPlz Avatar answered Nov 03 '22 01:11

SudoPlz


It seems we can use @Override public void onCatalystInstanceDestroy() {} without the need of implementing anything. That method will be called before the current JS bundle is destroyed.

like image 27
user3621841 Avatar answered Nov 03 '22 01:11

user3621841