Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: Get Lifecycle or LifecycleOwner in native module

I'm developing a native module for React Native which wraps the CameraX API. The CameraX API is a lifecycle-aware API, so it requires me to pass an androidx Lifecycle (or androidx LifecycleOwner) into it's constructor.

Since those are androidx classes, there's no way to obtain a Lifecycle (or LifecycleOwner) from the React Native context.

There is however ReactContext::addLifecycleEventListener, which is a custom lifecycle event listener implementation by React Native (LifecycleEventListener), which I am now trying to "convert"/map to an androidx Lifecycle (or LifecycleOwner), but I can't figure out how.

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)

My question is now: How do I "create" a Lifecycle (or LifecycleOwner) instance from my React lifecycle?

I'd appreciate any kind of help.

like image 688
mrousavy Avatar asked Jul 26 '26 19:07

mrousavy


1 Answers

The solution is to cast the current activity from the react context:

private val lifecycle: Lifecycle by lazy {
    ((context as ReactContext).currentActivity as AppCompatActivity).lifecycle
}
like image 110
mrousavy Avatar answered Jul 28 '26 09:07

mrousavy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!