Search code examples
androidkotlinreact-nativeandroidx

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.


Solution

  • 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
    }