【问题标题】:React Native: Get Lifecycle or LifecycleOwner in native moduleReact Native:在原生模块中获取 Lifecycle 或 LifecycleOwner
【发布时间】:2021-01-12 13:35:13
【问题描述】:

我正在为 React Native 开发一个原生模块,它封装了 CameraX API。 CameraX API 是一个生命周期感知 API,因此它需要我将 androidx Lifecycle(或 androidx LifecycleOwner)传递给它的构造函数。

由于这些是 androidx 类,因此无法从 React Native 上下文中获取 Lifecycle(或 LifecycleOwner)。

但是有 ReactContext::addLifecycleEventListener,这是 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)实例?

如果能提供任何帮助,我将不胜感激。

【问题讨论】:

    标签: android react-native kotlin react-native-android androidx


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-23
      • 1970-01-01
      • 2018-07-13
      相关资源
      最近更新 更多