harmony 鸿蒙Using Emitter for Inter-Thread Communication

  • 2023-02-03
  • 浏览 (720)

Using Emitter for Inter-Thread Communication

Emitter provides APIs for sending and processing events between threads, including the APIs for processing events that are subscribed to in persistent or one-shot manner, unsubscribing from events, and emitting events to the event queue.

To develop the Emitter mode, perform the following steps:

  1. Subscribe to an event.
   import emitter from "@ohos.events.emitter";

   // Define an event with eventId 1.
   let event: emitter.InnerEvent = {
     eventId: 1
   };

   // Trigger the callback after the event with eventId 1 is received.
   let callback = (eventData: emitter.EventData) => {
     console.info('event callback');
   };

   // Subscribe to the event with eventId 1.
   emitter.on(event, callback);
  1. Emit the event.
   import emitter from "@ohos.events.emitter";
   
   // Define an event with eventId 1 and priority Low.
   let event: emitter.InnerEvent = {
     eventId: 1,
     priority: emitter.EventPriority.LOW
   };
   
   let data = new Map<string, Object>();
   data.set("content", "c");
   data.set("id", 1);
   data.set("isEmpty", false);
   let eventData: emitter.EventData = {data};
   
   // Emit the event with eventId 1 and event content eventData.
   emitter.emit(event, eventData);

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Application Models

harmony 鸿蒙Using Explicit Want to Start an Application Component

harmony 鸿蒙Using Implicit Want to Open a Website

harmony 鸿蒙AbilityStage Component Container

harmony 鸿蒙Accessing a DataAbility

harmony 鸿蒙Accessing a DataShareExtensionAbility from the FA Model

harmony 鸿蒙AccessibilityExtensionAbility

harmony 鸿蒙Common action and entities Values

harmony 鸿蒙API Switching Overview

harmony 鸿蒙Switching of app and deviceConfig

0  赞