React Native:获取原生模块中的Lifecycle或LifecycleOwner

React Native: Get Lifecycle or LifecycleOwner in native module

我正在为 React Native 开发一个原生模块,它包装了 CameraX API。 CameraX API 是生命周期感知的 API,所以它需要我将 androidx Lifecycle (or androidx LifecycleOwner) 传递到它的构造函数中。

因为它们是 androidx 类,所以无法从 React Native 上下文中获取 Lifecycle(或 LifecycleOwner)。

但是有 ReactContext::addLifecycleEventListener, which is a custom lifecycle event listener implementation by React Native (LifecycleEventListener),我现在正试图将其“转换”/映射到 androidx Lifecycle(或 LifecycleOwner),但我无法弄清楚怎么样。

val lifecycle: Lifecycle = ???

reactContext.addLifecycleEventListener(object : LifecycleEventListener {
    override fun onHostResume() {
        TODO("Not yet implemented")
    }

    override fun onHostPause() {
        TODO("Not yet implemented")
    }

    override fun onHostDestroy() {
        TODO("Not yet implemented")
    }
})

cameraProvider.bindToLifecycle(lifecycle, cameraSelector, preview)

我现在的问题是:如何从我的 React 生命周期“创建”一个 Lifecycle(或 LifecycleOwner)实例?

如有任何帮助,我将不胜感激。

解决方案是从反应上下文中转换当前activity:

private val lifecycle: Lifecycle by lazy {
    ((context as ReactContext).currentActivity as AppCompatActivity).lifecycle
}