• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Using Emitter for Inter-Thread Communication
2
3[Emitter](../../reference/apis-basic-services-kit/js-apis-emitter.md) 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.
4
5To develop the Emitter mode, perform the following steps:
6
71. Subscribe to an event.
8
9   ```ts
10   import { emitter } from '@kit.BasicServicesKit';
11   import { promptAction } from '@kit.ArkUI';
12   import { hilog } from '@kit.PerformanceAnalysisKit';
13
14   const TAG: string = 'ThreadModel';
15   const DOMAIN_NUMBER: number = 0xFF00;
16   ```
17   ```ts
18   // Define an event with eventId 1.
19   let event: emitter.InnerEvent = {
20     eventId: 1
21   };
22
23   // Trigger the callback after the event with eventId 1 is received.
24   let callback = (eventData: emitter.EventData): void => {
25     promptAction.showToast({
26       message: JSON.stringify(eventData)
27     });
28     hilog.info(DOMAIN_NUMBER, TAG, 'event callback:' + JSON.stringify(eventData));
29   };
30
31   // Subscribe to the event with eventId 1.
32   emitter.on(event, callback);
33   promptAction.showToast({
34     message: JSON.stringify('emitter subscribe success')
35   });
36   ```
37
382. Emit the event.
39   ```ts
40   // Define an event with eventId 1 and priority Low.
41   let event: emitter.InnerEvent = {
42     eventId: 1,
43     priority: emitter.EventPriority.LOW
44   };
45
46   let eventData: emitter.EventData = {
47     data: {
48       content: 'c',
49       id: 1,
50       isEmpty: false
51     }
52   };
53
54   // Emit the event with eventId 1 and event content eventData.
55   emitter.emit(event, eventData);
56   ```
57