Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

android - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...