DEV Community

HarmonyOS
HarmonyOS

Posted on

How to solve the problem of multiple instantiation failures of XComponent components

Read the original article:How to solve the problem of multiple instantiation failures of XComponent components

How to solve the problem of multiple instantiation failures of XComponent components

Problem description

Because the video surveillance application needs to switch the surveillance screen between multiple cameras, jumping to the page will involve XComponent component initialization and resource release. After the component is initialized for the second time, the application crashes when exiting the page.

Background knowledge

As a drawing component, XComponent is usually used to meet developers' more complex custom drawing requirements, such as displaying camera preview streams and drawing game screens.
Native XCompnent is an instance of the XComponent component provided in the Native layer, which can be used as a bridge for binding XComponent in the JS layer and the Native layer.

Solution

The code example is as follows:

import { OpenGLView } from '../view/OpenGLView';
import { YUVView } from '../view/YUVView';
import { CommonConstant as Common } from '../common/CommonConstant';

@Entry
@Component
struct Index {
  @State currentIndex: number = 0;

  @Builder
  tabBuilder(index: number, name: ResourceStr) {
    Column() {
     ...
  }

  build() {
    Column() {
    ...

      Tabs({ barPosition: BarPosition.Start, index: this.currentIndex }) {

        ...

        TabContent() {
          if (this.currentIndex == 1)
          {
            YUVView()
          }
        }
        .tabBar(this.tabBuilder(1, $r('app.string.yuv_draw')))
      }
      .onChange((index: number) => {
        this.currentIndex = index;
      })
      .width(Common.FULL_PERCENT)

    ...
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The core difference is that a judgment condition is added: this.currentIndex == 1. After the condition is met, YUVView() is rendered, and the second creation of XComponent crashes.

The rendering mechanism of if/else is that whenever the state variable used in the if or else if conditional statement changes, the conditional statement will be updated and the new conditional value will be re-evaluated. If the conditional value evaluation changes, it means that another conditional branch needs to be built. At this time, the ArkUI framework will: Delete all previously rendered (earlier branch) components. Execute the constructor of the new branch and add the generated child component to its parent component. The second creation of XComponent cannot be circumvented by adding a random number to the previous id.

The code example is as follows:

id: Common.YUV_XCOMPONENT_ID + Math.random().toString()
Enter fullscreen mode Exit fullscreen mode

Written by Emine Inan

Top comments (0)