HarmonyOS NEXT实战:使用Emitter进行线程间通信

8 阅读2分钟

##HarmonyOS Next实战##HarmonyOS SDK应用服务##教育##

参考资料: developer.huawei.com/consumer/cn…

Emitter是一种作用在进程内的事件处理机制,为应用程序提供订阅事件、发布事件、取消事件订阅的能力。

场景介绍: Emitter用于同一进程内相同线程或不同线程间的事件处理,事件异步执行。使用时需要先订阅一个事件,然后发布该事件,发布完成后Emitter会将已发布的事件分发给订阅者,订阅者就会执行该事件订阅时设置的回调方法。当不需要订阅该事件时应及时取消订阅释放Emitter资源。

运作机制: Emitter通过维护一个内部事件队列,来进行任务分发。应用需要先订阅某个事件并设置好该事件的回调方法,当应用程序发布事件后,就会往队列里面插入一个事件。任务队列会串行执行队列里面的任务,执行任务时会调用该任务订阅者的回调方法进行事件处理。

接口说明:

  • emit : 发布事件一次。
  • on : 持续订阅事件,直至该事件被取消订阅。
  • once : 订阅事件一次。
  • off : 取消所有订阅事件。取消事件订阅后,所有订阅事件将不再接收该事件的消息。

取消事件订阅说明:

  • 当不需要订阅某个事件时,需要及时取消订阅避免造成内存泄漏。
  • 使用off接口取消某个事件订阅后,已通过emit接口发布但尚未被执行的事件将被取消。

代码示例:

import { emitter } from '@kit.BasicServicesKit'

@Entry
@Component
struct EmitterPage {
  @State onResult: string = 'Emitter.on result is : '
  @State onceResult: string = 'Emitter.once result is : '
  @State emitResult: string = 'Emitter.emit result is : '
  @State count: number = 0

  build() {
    Column({ space: 10 }) {
      Text('Emitter Page')
        .fontSize(20)
        .fontWeight(FontWeight.Bold)

      Text(`count=${this.count}`)

      Button('Emitter.on').onClick(() => {
        // 定义一个eventId为1的事件。
        let event: emitter.InnerEvent = {
          eventId: 1
        };
        // 定义一个事件的回调处理函数,当收到对应的事件后执行回调函数
        let callback: Callback<emitter.EventData> = (eventData: emitter.EventData) => {
          console.info(`eventData: ${JSON.stringify(eventData)}`);
          this.onResult = JSON.stringify(eventData)
        }
        // 收到eventId为1的事件后执行回调函数
        emitter.on(event, callback);
      })
      Text(this.onResult)

      Button('Emitter.once').onClick(() => {
        // 定义一个eventId为1的事件。
        let event: emitter.InnerEvent = {
          eventId: 1
        };
        // 定义一个事件的回调处理函数,当收到对应的事件后执行回调函数
        let callback: Callback<emitter.EventData> = (eventData: emitter.EventData) => {
          console.info(`eventData: ${JSON.stringify(eventData)}`);
          this.onceResult = JSON.stringify(eventData)
        }
        // 收到eventId为1的事件后执行回调函数
        emitter.once(event, callback);
      })
      Text(this.onceResult)

      Button('Emitter.emit').onClick(() => {
        this.count = this.count + 1
        // 定义一个eventId为1的事件,事件优先级为Low。
        let event: emitter.InnerEvent = {
          eventId: 1,
          priority: emitter.EventPriority.LOW
        };
        let eventData: emitter.EventData = {
          data: {
            content: 'emitter',
            count: this.count,
            id: 1,
            isEmpty: false
          }
        };
        // 发送eventId为1的事件,事件内容为eventData。
        emitter.emit(event, eventData);
      })
      Text(this.emitResult)

      Button('Emitter.off').onClick(() => {
        // 取消eventId为1的事件。
        emitter.off(1);
      })
    }
    .height('100%')
    .width('100%')
  }
}