React Native - 模块生命周期 - 在 "Reload" 上处置资源

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

我正在使用 React Native 模块 (https://github.com/rusel1989/react-native-bluetooth-serial) 与 Arduino 进行蓝牙通信。

一切正常。但是当我按下 "Reload" 或由于启用了实时重新加载而重新加载应用程序时,不会调用模块的 onDestroy 方法。因此,套接字(和流)没有正确处理。

重新加载完成后,我无法再打开蓝牙插座。它需要我禁用和启用蓝牙,或重新启动应用程序。

有没有我可以实现的 ant 回调或方法,可以在我重新加载我的应用程序时正确处理这些套接字?

看来我们可以使用 @Override public void onCatalystInstanceDestroy() {} 而无需执行任何操作。 该方法将在当前 JS 包被销毁之前被调用。

好的,在花时间研究本机代码后,我找到了答案:

上 iOS:

您必须在 RCTBridgeModule 实现中实现一个名为 invalidate 的方法:

只要上下文被销毁(应用程序重新加载),它就会 运行 并且它看起来像这样:

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

这是 an example 我在 iOS 上的做法。

上 Android:

您必须在 ReactContextBaseJavaModule 中实现 onCatalystInstanceDestroy 方法,它看起来像这样:

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

这是 an example 我在 Android 上的做法。

在 iOS

- (instancetype)init
{
    self = [super init];
       
    NSLog(@"whatever you want");
    
    return self;
}

- (void)dealloc
{
    // by the way, you do not need the following line because of ARC
    // [super dealloc];

    NSLog(@"whatever you want");
}

我更喜欢使用 dealloc 而不是 invalidate 因为 react-native api 将来可能会改变...

于 android

import com.facebook.react.bridge.LifecycleEventListener;
import android.util.Log;

public class YourModule extends ReactContextBaseJavaModule implements LifecycleEventListener {

    ...

    YourModule(ReactApplicationContext reactContext) {
        super(reactContext);
        reactContext.addLifecycleEventListener(this);
        this.reactContext = reactContext;
        Log.d("YourModuleLog", "whatever you want");
    }

    @Override
    public void onHostResume() {}

    @Override
    public void onHostPause() {}

    @Override
    public void onHostDestroy() {
        Log.d("YourModuleLog", "not trigger after fast reload");
    }

    @Override
    public void onCatalystInstanceDestroy() {
        Log.d("YourModuleLog", "whatever you want");
    }
}

仅覆盖 onCatalystInstanceDestroy 对我不起作用 除非我也添加 LifecycleEventListener.