Call the corresponding .off() method in a timely manner after .on() finishes to unregister the listener and prevent memory leaks. inspector.ComponentObserver is the handle for callbacks triggered upon completion of component layout and rendering display. Callbacks are registered to the corresponding query condition through this handle and invoked when component layout completes.
// rules.json
{
"rules": {
"arkts": {
"ResourceLeak": [
{
"ruleId": "ComponentObserverListenerNotOff",
"severity": "error",
"skip": false
}
]
}
}
} import { inspector } from '@kit.ArkUI';
/**
* Positive example: Resources are correctly released.
*/
@Component
struct TestRelease {
private listenerForImage: inspector.ComponentObserver = this.getUIContext().getUIInspector().createComponentObserver('IMAGE_ID')
private listenerForRow: inspector.ComponentObserver = this.getUIContext().getUIInspector().createComponentObserver('ROW_ID')
private onLayoutComplete: () => void = (): void => {
console.log('This is onLayoutComplete callback');
}
private onDrawComplete: () => void = (): void => {
console.log('This is onDrawComplete callback');
}
private onDrawChildrenComplete: () => void = (): void => {
console.log('This is onDrawChildrenComplete callback');
}
aboutToAppear() {
this.listenerForImage.on('layout', this.onLayoutComplete)
this.listenerForImage.on('draw', this.onDrawComplete)
this.listenerForRow.on('drawChildren', this.onDrawChildrenComplete)
}
aboutToDisappear() {
this.listenerForImage.off('layout', this.onLayoutComplete)
this.listenerForImage.off('draw', this.onDrawComplete)
this.listenerForRow.off('drawChildren', this.onDrawChildrenComplete)
}
build() {
Text('This is build')
}
} import { inspector } from '@kit.ArkUI';
/**
* Negative example: Resources are not released.
*/
@Component
struct TestNotRelease {
private listenerForImage: inspector.ComponentObserver = this.getUIContext().getUIInspector().createComponentObserver('IMAGE_ID')
private listenerForRow: inspector.ComponentObserver = this.getUIContext().getUIInspector().createComponentObserver('ROW_ID')
private onLayoutComplete: () => void = (): void => {
console.log('This is onLayoutComplete callback');
}
private onDrawComplete: () => void = (): void => {
console.log('This is onDrawComplete callback');
}
private onDrawChildrenComplete: () => void = (): void => {
console.log('This is onDrawChildrenComplete callback');
}
aboutToAppear() {
this.listenerForImage.on('layout', this.onLayoutComplete)
this.listenerForImage.on('draw', this.onDrawComplete) // leak
this.listenerForRow.on('drawChildren', this.onDrawChildrenComplete)
}
aboutToDisappear() {
this.listenerForImage.off('layout', this.onLayoutComplete)
this.listenerForRow.off('drawChildren', this.onDrawChildrenComplete)
}
build() {
Text('This is build')
}
} For details about how to configure Code Scanner check rules, see Using codescanner.