• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# EventHub
2
3<!--Kit: Ability Kit-->
4<!--Subsystem: Ability-->
5<!--Owner: @zexin_c-->
6<!--Designer: @li-weifeng2-->
7<!--Tester: @lixueqing513-->
8<!--Adviser: @huipeizi-->
9
10EventHub is an event communication mechanism based on the publish-subscribe pattern. It decouples senders and subscribers through event names, supporting efficient data transfer and state synchronization between different service modules. It is primarily used for [data communication between UIAbility components and UI pages](../../application-models/uiability-data-sync-with-ui.md).
11
12Different Context objects have different EventHub objects, and different EventHub objects cannot communicate directly with each other. Event subscription, unsubscription, and triggering all take place on a specific EventHub object.
13
14Since Worker and TaskPool implement [multithreaded concurrency](../../arkts-utils/multi-thread-concurrency-overview.md#multithreaded-concurrency-models) through the actor model, where different virtual machine instances have exclusive memory, EventHub objects cannot be used for inter-thread data communication.
15
16
17> **NOTE**
18>
19>  - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
20>  - The APIs of this module can be used only in the stage model.
21
22## Constraints
23
24- EventHub cannot be used for data communication between processes.
25- EventHub cannot be used for data communication between Worker or TaskPool threads. Instead, use [Emitter for inter-thread communication](../../basic-services/common-event/itc-with-emitter.md).
26- Data communication between EventHub objects of different Context objects within the same thread is not supported.
27- A Context object converted by [sendableContextManager](js-apis-app-ability-sendableContextManager.md) is considered different from the original Context object, and data communication between their EventHub objects is not supported.
28
29## Modules to Import
30
31```ts
32import { common } from '@kit.AbilityKit';
33```
34
35## Usage
36
37You need to obtain an EventHub object through a Context object. The following example demonstrates how to obtain the EventHub object of a UIAbility instance's Context object.
38
39```ts
40import { common, UIAbility } from '@kit.AbilityKit';
41
42export default class EntryAbility extends UIAbility {
43  eventFunc() {
44    console.log('eventFunc is called');
45  }
46
47  onCreate() {
48    // Method 1 (recommended)
49    this.context.eventHub.on('myEvent', this.eventFunc);
50
51    // Method 2
52    let eventhub = this.context.eventHub as common.EventHub;
53    eventhub.on('myEvent', this.eventFunc);
54  }
55}
56```
57
58## EventHub.on
59
60on(event: string, callback: Function): void;
61
62Subscribes to an event.
63> **NOTE**
64>
65>  When the callback is triggered by **emit**, the invoker is the EventHub object. To change the direction of **this** in **callback**, use an arrow function.
66
67**Atomic service API**: This API can be used in atomic services since API version 11.
68
69**System capability**: SystemCapability.Ability.AbilityRuntime.Core
70
71**Parameters**
72
73| Name| Type| Mandatory| Description|
74| -------- | -------- | -------- | -------- |
75| event | string | Yes| Event name.|
76| callback | Function | Yes| Callback invoked when the event is triggered.|
77
78**Error codes**
79
80For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
81
82| ID| Error Message|
83| ------- | -------- |
84| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
85
86**Example 1**
87When the callback is triggered by **emit**, the invoker is the EventHub object. The EventHub object does not have the **value** property. Therefore, the result **undefined** is returned.
88
89```ts
90import { UIAbility } from '@kit.AbilityKit';
91import { BusinessError } from '@kit.BasicServicesKit';
92
93export default class EntryAbility extends UIAbility {
94  value: number = 12;
95
96  onCreate() {
97    try {
98      this.context.eventHub.on('myEvent', this.eventFunc);
99    } catch (e) {
100      let code: number = (e as BusinessError).code;
101      let msg: string = (e as BusinessError).message;
102      console.error(`EventHub emit error, code: ${code}, msg: ${msg}`);
103    }
104  }
105
106  onForeground() {
107    try {
108      // Result
109      // eventFunc is called, value: undefined
110      this.context.eventHub.emit('myEvent');
111    } catch (e) {
112      let code: number = (e as BusinessError).code;
113      let msg: string = (e as BusinessError).message;
114      console.error(`EventHub emit error, code: ${code}, msg: ${msg}`);
115    }
116  }
117
118  eventFunc() {
119    console.log(`eventFunc is called, value: ${this.value}`);
120  }
121}
122```
123
124**Example 2**
125When the callback uses an arrow function, the invoker is the EntryAbility object. The EntryAbility object has the **value** property. Therefore, the result **12** is returned.
126
127```ts
128import { UIAbility } from '@kit.AbilityKit';
129import { BusinessError } from '@kit.BasicServicesKit';
130
131export default class EntryAbility extends UIAbility {
132  value: number = 12;
133
134  onCreate() {
135    try {
136      // Anonymous functions can be used to subscribe to events.
137      this.context.eventHub.on('myEvent', () => {
138        console.log(`anonymous eventFunc is called, value: ${this.value}`);
139      });
140    } catch (e) {
141      let code: number = (e as BusinessError).code;
142      let msg: string = (e as BusinessError).message;
143      console.error(`EventHub emit error, code: ${code}, msg: ${msg}`);
144    }
145  }
146
147  onForeground() {
148    try {
149      // Result
150      // anonymous eventFunc is called, value: 12
151      this.context.eventHub.emit('myEvent');
152    } catch (e) {
153      let code: number = (e as BusinessError).code;
154      let msg: string = (e as BusinessError).message;
155      console.error(`EventHub emit error, code: ${code}, msg: ${msg}`);
156    }
157  }
158
159  eventFunc() {
160    console.log(`eventFunc is called, value: ${this.value}`);
161  }
162}
163```
164
165## EventHub.off
166
167off(event: string, callback?: Function): void;
168
169Unsubscribes from an event.
170 - If **callback** is specified, this API unsubscribes from the given event with the specified callback.
171 - If **callback** is not specified, this API unsubscribes from the given event with all callbacks.
172
173**Atomic service API**: This API can be used in atomic services since API version 11.
174
175**System capability**: SystemCapability.Ability.AbilityRuntime.Core
176
177**Parameters**
178
179| Name| Type| Mandatory| Description|
180| -------- | -------- | -------- | -------- |
181| event | string | Yes| Event name.|
182| callback | Function | No| Callback for the event. If **callback** is unspecified, the given event with all callbacks is unsubscribed.|
183
184**Error codes**
185
186For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
187
188| ID| Error Message|
189| ------- | -------- |
190| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
191
192**Example**
193
194```ts
195import { UIAbility } from '@kit.AbilityKit';
196import { BusinessError } from '@kit.BasicServicesKit';
197
198export default class EntryAbility extends UIAbility {
199  onCreate() {
200    try {
201      this.context.eventHub.on('myEvent', this.eventFunc1);
202      this.context.eventHub.off('myEvent', this.eventFunc1); // Unsubscribe from the myEvent event with the callback eventFunc1.
203      this.context.eventHub.on('myEvent', this.eventFunc1);
204      this.context.eventHub.on('myEvent', this.eventFunc2);
205      this.context.eventHub.off('myEvent'); // Unsubscribe from the myEvent event with all the callbacks (eventFunc1 and eventFunc2).
206    } catch (e) {
207      let code: number = (e as BusinessError).code;
208      let msg: string = (e as BusinessError).message;
209      console.error(`EventHub emit error, code: ${code}, msg: ${msg}`);
210    }
211  }
212
213  eventFunc1() {
214    console.log('eventFunc1 is called');
215  }
216
217  eventFunc2() {
218    console.log('eventFunc2 is called');
219  }
220}
221```
222
223## EventHub.emit
224
225emit(event: string, ...args: Object[]): void;
226
227Triggers an event.
228
229**Atomic service API**: This API can be used in atomic services since API version 11.
230
231**System capability**: SystemCapability.Ability.AbilityRuntime.Core
232
233**Parameters**
234
235| Name| Type| Mandatory| Description|
236| -------- | -------- | -------- | -------- |
237| event | string | Yes| Event name.|
238| ...args | Object[] | No| Variable parameters, which are passed to the callback when the event is triggered.|
239
240**Error codes**
241
242For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
243
244| ID| Error Message|
245| ------- | -------- |
246| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
247
248**Example**
249
250```ts
251import { UIAbility } from '@kit.AbilityKit';
252import { BusinessError } from '@kit.BasicServicesKit';
253
254export default class EntryAbility extends UIAbility {
255  onCreate() {
256    this.context.eventHub.on('myEvent', this.eventFunc);
257  }
258
259  onDestroy() {
260    try {
261      // Result
262      // eventFunc is called,undefined,undefined
263      this.context.eventHub.emit('myEvent');
264      // Result
265      // eventFunc is called,1,undefined
266      this.context.eventHub.emit('myEvent', 1);
267      // Result
268      // eventFunc is called,1,2
269      this.context.eventHub.emit('myEvent', 1, 2);
270    } catch (e) {
271      let code: number = (e as BusinessError).code;
272      let msg: string = (e as BusinessError).message;
273      console.error(`EventHub emit error, code: ${code}, msg: ${msg}`);
274    }
275  }
276
277  eventFunc(argOne: number, argTwo: number) {
278    console.log(`eventFunc is called, ${argOne}, ${argTwo}`);
279  }
280}
281```
282