鸿蒙:使用EventHub实现多模块之间的通信

前言:

官方文档上指出,EventHub是系统提供的基于发布-订阅模式实现的事件通信机制。通过事件名,实现了发送方和订阅方之间的解耦,支持不同业务模块间的高效数据传递和状态同步。

主要用于UIAbility组件与UI的数据通信。

还是老样子,在学习新知识之前,我们应当参考官方文档和示例,链接如下:

文档中心https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-inner-application-eventhub看完了文档,相信你对EventHub有了了解,那么我们就来实践演练吧。

这里就不多解释,我已经封装好了,直接上效果图和代码:

代码如下:

1、EventHubUtil.ets

复制代码
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { promptAction } from '@kit.ArkUI';

class EventHubUtil {
  context: common.UIAbilityContext = AppStorage.get('appStorage') as common.UIAbilityContext
  value: number = 0;

  eventFunc() {
    console.log('eventFunc is called');
  }

  // 订阅事件
  on() {

    try {
      // 支持使用匿名函数订阅事件
      this.context.eventHub.on('myEvent', () => {
        console.log(`anonymous eventFunc is called, value: ${this.value}`);
      });
      promptAction.showToast({ message: "订阅成功!" })
    } catch (e) {
      let code: number = (e as BusinessError).code;
      let msg: string = (e as BusinessError).message;
      console.error(`EventHub emit error, code: ${code}, msg: ${msg}`);
    }


  }

  // 发送事件
  emit() {
    this.value++
    try {
      // 结果:
      // anonymous eventFunc is called, value: 12
      this.context.eventHub.emit('myEvent');
      promptAction.showToast({ message: "发送成功!" })
    } catch (e) {
      let code: number = (e as BusinessError).code;
      let msg: string = (e as BusinessError).message;
      console.error(`EventHub emit error, code: ${code}, msg: ${msg}`);
    }
  }

  // 取消事件
  off() {
    this.context.eventHub.off('myEvent');
    promptAction.showToast({ message: "取消成功!" })
  }
}

export const eventHubUtil = new EventHubUtil();

2、Index.ets

复制代码
import { emitterUtil } from "./EmitterUtil"
import { eventHubUtil } from "./EventHubUtil"

// emitter使用示例
@Entry
@Component
export struct Index {
  build() {
    Column({ space: 20 }) {
      // Button("emitter.fire")
      //   .onClick(() => {
      //     emitterUtil.fire()
      //
      //   })
      //
      // Button("emitter.on")
      //   .onClick(() => {
      //     emitterUtil.on()
      //
      //   })
      //
      // Button("emitter.off")
      //   .onClick(() => {
      //     emitterUtil.off()
      //
      //   })


      Button("EventHub.emit")
        .onClick(() => {
          eventHubUtil.emit()
        })

      Button("EventHub.on")
        .onClick(() => {
          eventHubUtil.on()
        })

      Button("EventHub.off")
        .onClick(() => {
          eventHubUtil.off()
        })
    }
    .width("100%")
    .height("100%")
    .justifyContent(FlexAlign.Center)
    .alignItems(HorizontalAlign.Center)

  }
}

以上是个人经验分享。

······················

补充一下,EntryAbility.ets中需要添加的内容:

找到onCreate方法:

复制代码
    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
      // 存储UIAbilityContext
      AppStorage.setOrCreate('appStorage', this.context)
}
相关推荐
一只大侠的侠30 分钟前
Flutter开源鸿蒙跨平台训练营 Day 4实现流畅的下拉刷新与上拉加载效果
flutter·开源·harmonyos
早點睡3901 小时前
高级进阶 ReactNative for Harmony 项目鸿蒙化三方库集成实战:react-native-drag-sort
react native·react.js·harmonyos
果粒蹬i1 小时前
【HarmonyOS】DAY9:利用React Native开发底部 Tab 开发实战:从问题定位到最佳实践
华为·harmonyos
lbb 小魔仙2 小时前
【HarmonyOS实战】OpenHarmony + RN:自定义 useForm 表单管理
harmonyos
早點睡3902 小时前
高级进阶 ReactNative for Harmony 项目鸿蒙化三方库集成实战:react-native-video
react native·华为·harmonyos
开开心心就好2 小时前
发票合并打印工具,多页布局设置实时预览
linux·运维·服务器·windows·pdf·harmonyos·1024程序员节
前端不太难3 小时前
HarmonyOS 游戏项目,从 Demo 到可上线要跨过哪些坑
游戏·状态模式·harmonyos
全栈探索者3 小时前
列表渲染不用 map,用 ForEach!—— React 开发者的鸿蒙入门指南(第 4 期)
react.js·harmonyos·arkts·foreach·列表渲染
试着5 小时前
【huawei】机考整理
学习·华为·面试·机试
一只大侠的侠5 小时前
Flutter开源鸿蒙跨平台训练营 Day8获取轮播图网络数据并实现展示
flutter·开源·harmonyos