DEV Community

victordeng
victordeng

Posted on

HarmonyOS NEXT project practice:Using an emitter for inter thread communication

reference material:
https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/itc-with-emitter

An emitter is an event handling mechanism that operates within a process, providing applications with the ability to subscribe to events, publish events, and unsubscribe from events.

Scene introduction:
The emitter is used for event processing within the same process or between different threads, with asynchronous execution of events. When using, you need to subscribe to an event first, and then publish the event. After the publication is completed, the emitter will distribute the published event to the subscribers, and the subscribers will execute the callback method set when subscribing to the event. When there is no need to subscribe to the event, the subscription should be cancelled in a timely manner to release the emitter resources.

Operating mechanism:
The emitter distributes tasks by maintaining an internal event queue. The application needs to subscribe to an event and set the callback method for that event first. After the application publishes the event, it will insert an event into the queue. The task queue will execute the tasks in the queue sequentially, and the callback method of the task subscriber will be called for event processing during task execution.

Interface Description:

  • Send: Publish an event once.
  • On: Continuously subscribe to the event until it is unsubscribed.
  • Once: Subscribe to an event once.
  • Off: Cancel all subscription events. After canceling the event subscription, all subscribed events will no longer receive messages for that event.

Instructions for canceling event subscription:

  • When there is no need to subscribe to an event, it is necessary to unsubscribe in a timely manner to avoid memory leaks.
  • After using the off interface to unsubscribe from an event, events that have been published through the emit interface but have not yet been executed will be canceled.

Code example:

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%')
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)