使用了这个三方库ohpm install @ohos/liveeventbus。
使用代码如下:发现 @State eventBus:不能更新UI。
const KEY_TEST_CLOSE_ALL_PAGE = "key_test_close_all_page";
@Entry
@Component
struct EventBusPage {
mLifecycle: Lifecycle = new Lifecycle(MState.STARTED);
@State eventBus: boolean = false;
aboutToAppear(): void {
//创建生命周期感知对象
this.mLifecycle = new Lifecycle(MState.STARTED)
//订阅消息
LiveEventBus
.get<boolean>(KEY_TEST_CLOSE_ALL_PAGE)
.observe(this, {
onChanged(b: boolean) {
this.eventBus = b;
}
});
}
build() {
Row() {
Column() {
Text('LiveEventBus Demo' + this.eventBus)
.fontSize(30)
.fontWeight(FontWeight.Bold)
}.onClick((e) => {
//发送消息
LiveEventBus.get(KEY_TEST_CLOSE_ALL_PAGE).post( !this.eventBus);
})
.width('100%')
}
.height('100%')
}
//生命周期感知对象
getLifecycle(): Lifecycle {
return this.mLifecycle
}
}
eventBus的使用请参考文档:https://gitee.com/openharmony-sig/LiveEventBus,demo中onchanged方法中的this对应的不是页面的this,所以不会发生变化可以参考此demo: