• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.app.ability.sendableContextManager (Sendable Context Management)
2
3<!--Kit: Ability Kit-->
4<!--Subsystem: Ability-->
5<!--Owner: @zhangyafei-echo; @xuzhihao666-->
6<!--Designer: @zhangyafei-echo-->
7<!--Tester: @lixueqing513-->
8<!--Adviser: @huipeizi-->
9
10The sendableContextManager module provides APIs for converting between Context and [SendableContext](js-apis-inner-application-sendableContext.md) objects.
11
12> **NOTE**
13>
14> - The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version.
15> - The APIs of this module can be used only in the stage model.
16
17## When to Use
18
19This module is used to transfer data between concurrent ArkTS instances (including the main thread and the worker thread of TaskPool or Worker).
20
21For example, when transferring sendable data from the main thread to a child thread, the following conversion steps are involved to ensure efficient data transfer:
22- Conversion from Context to SendableContext for the main thread to transfer sendable data to the child thread.
23- Conversion from SendableContext to Context for the child thread to use the sendable data.
24
25The Context here is different from that created by [createModuleContext](./js-apis-app-ability-application.md#applicationcreatemodulecontext12). The differences are as follows:
26- Context involved in the conversion: ArkTS concurrent instances hold different application-side Context instances that correspond to the same underlying Context object. When the Context properties and methods in an instance are modified, the Context properties and methods in the related instances are modified accordingly. The eventHub attribute in the Context instance is special. The eventHub objects in different instances are independent of each other and cannot be used across ArkTS instances. If you want to use [EventHub](./js-apis-inner-application-eventHub.md) to transfer data across instances, call [setEventHubMultithreadingEnabled](#sendablecontextmanagerseteventhubmultithreadingenabled20) to enable the cross-thread data transfer feature.
27
28
29- Context created using [createModuleContext](./js-apis-app-ability-application.md#applicationcreatemodulecontext12): ArkTS concurrent instances hold different application-side Context objects that correspond to different underlying Context objects.
30
31## Constraints
32
33The Context types used in the conversion must be the same. Currently, the following types of Context support conversion: [Context](js-apis-inner-application-context.md), [ApplicationContext](js-apis-inner-application-applicationContext.md), [AbilityStageContext](js-apis-inner-application-abilityStageContext.md), and [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md).
34
35## Modules to Import
36
37```ts
38import { sendableContextManager } from '@kit.AbilityKit';
39```
40
41## SendableContext
42
43type SendableContext = _SendableContext
44
45Defines the Sendable context. It complies with the [Sendable protocol](../../arkts-utils/arkts-sendable.md#sendable-protocol) and inherits from [lang.ISendable](../apis-arkts/js-apis-arkts-lang.md#langisendable).
46
47**System capability**: SystemCapability.Ability.AbilityRuntime.Core
48
49**Atomic service API**: This API can be used in atomic services since API version 12.
50
51| Type| Description|
52| --- | --- |
53| [_SendableContext](js-apis-inner-application-sendableContext.md) | Sendable context, which can be converted to a Context object to implement data transmission between concurrent ArkTS instances (including the main thread and the worker thread of TaskPool or Worker).|
54
55## sendableContextManager.convertFromContext
56
57convertFromContext(context: common.Context): SendableContext
58
59Converts a Context object to a SendableContext object.
60
61**System capability**: SystemCapability.Ability.AbilityRuntime.Core
62
63**Atomic service API**: This API can be used in atomic services since API version 12.
64
65**Parameters**
66
67| Name| Type| Mandatory| Description|
68| ------- | ------- | ------- | ------- |
69| context | [common.Context](js-apis-inner-application-context.md) | Yes| Context object. The Context base class, and its child classes [ApplicationContext](js-apis-inner-application-applicationContext.md), [AbilityStageContext](js-apis-inner-application-abilityStageContext.md), and [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) are supported.|
70
71**Return value**
72
73| Type| Description|
74| -------- | -------- |
75| SendableContext | [SendableContext](js-apis-inner-application-sendableContext.md) object.|
76
77**Error codes**
78
79For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
80
81| ID| Error Message|
82| ------- | ------- |
83| 401     | If the input parameter invalid. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
84
85**Example**
86
87```ts
88import { AbilityConstant, UIAbility, Want, sendableContextManager } from '@kit.AbilityKit';
89import { hilog } from '@kit.PerformanceAnalysisKit';
90import { worker } from '@kit.ArkTS';
91
92@Sendable
93export class SendableObject {
94  constructor(sendableContext: sendableContextManager.SendableContext) {
95    this.sendableContext = sendableContext;
96  }
97
98  sendableContext: sendableContextManager.SendableContext;
99  // other sendable object
100}
101
102export default class EntryAbility extends UIAbility {
103  worker: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
104
105  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
106    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
107
108    // convert and post
109    try {
110      let sendableContext: sendableContextManager.SendableContext = sendableContextManager.convertFromContext(this.context);
111      let object: SendableObject = new SendableObject(sendableContext);
112      hilog.info(0x0000, 'testTag', '%{public}s', 'Ability post message');
113      this.worker.postMessageWithSharedSendable(object);
114    } catch (error) {
115      hilog.error(0x0000, 'testTag', 'convertFromContext failed %{public}s', JSON.stringify(error));
116    }
117  }
118}
119```
120
121## sendableContextManager.convertToContext
122
123convertToContext(sendableContext: SendableContext): common.Context
124
125Converts a SendableContext object to a Context object.
126
127**System capability**: SystemCapability.Ability.AbilityRuntime.Core
128
129**Atomic service API**: This API can be used in atomic services since API version 12.
130
131**Parameters**
132
133| Name| Type| Mandatory| Description|
134| ------- | ------- | ------- | ------- |
135| sendableContext | [SendableContext](js-apis-inner-application-sendableContext.md) | Yes| SendableContext object.|
136
137**Return value**
138
139| Type| Description|
140| -------- | -------- |
141| common.Context | [Context](js-apis-inner-application-context.md) object.|
142
143**Error codes**
144
145For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
146
147| ID| Error Message|
148| ------- | ------- |
149| 401     | If the input parameter invalid. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
150
151**Example**
152
153Context passed by the main thread:
154```ts
155import { AbilityConstant, UIAbility, Want, common, sendableContextManager } from '@kit.AbilityKit';
156import { hilog } from '@kit.PerformanceAnalysisKit';
157import { worker } from '@kit.ArkTS';
158
159@Sendable
160export class SendableObject {
161  constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
162    this.sendableContext = sendableContext;
163    this.contextName = contextName;
164  }
165
166  sendableContext: sendableContextManager.SendableContext;
167  contextName: string;
168}
169
170export default class EntryAbility extends UIAbility {
171  worker: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
172
173  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
174    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
175
176    // convert and post
177    try {
178      let context: common.Context = this.context as common.Context;
179      let sendableContext: sendableContextManager.SendableContext = sendableContextManager.convertFromContext(context);
180      let object: SendableObject = new SendableObject(sendableContext, 'BaseContext');
181      hilog.info(0x0000, 'testTag', '%{public}s', 'Ability post message');
182      this.worker.postMessageWithSharedSendable(object);
183    } catch (error) {
184      hilog.error(0x0000, 'testTag', 'convertFromContext failed %{public}s', JSON.stringify(error));
185    }
186  }
187}
188```
189
190Context received by the Worker thread:
191```ts
192import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
193import { common, sendableContextManager } from '@kit.AbilityKit';
194import { hilog } from '@kit.PerformanceAnalysisKit';
195
196@Sendable
197export class SendableObject {
198  constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
199    this.sendableContext = sendableContext;
200    this.contextName = contextName;
201  }
202
203  sendableContext: sendableContextManager.SendableContext;
204  contextName: string;
205}
206
207const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
208
209workerPort.onmessage = (e: MessageEvents) => {
210  let object: SendableObject = e.data;
211  let sendableContext: sendableContextManager.SendableContext = object.sendableContext;
212  if (object.contextName == 'BaseContext') {
213    hilog.info(0x0000, 'testTag', '%{public}s', 'convert to context.');
214    try {
215      let context: common.Context = sendableContextManager.convertToContext(sendableContext);
216      // Obtain the sandbox path after obtaining the Context object.
217      hilog.info(0x0000, 'testTag', 'worker context.databaseDir: %{public}s', context.databaseDir);
218    } catch (error) {
219      hilog.error(0x0000, 'testTag', 'convertToContext failed %{public}s', JSON.stringify(error));
220    }
221  }
222}
223
224workerPort.onmessageerror = (e: MessageEvents) => {
225  hilog.info(0x0000, 'testTag', '%{public}s', 'onmessageerror');
226}
227
228workerPort.onerror = (e: ErrorEvent) => {
229  hilog.info(0x0000, 'testTag', '%{public}s', 'onerror');
230}
231```
232
233## sendableContextManager.convertToApplicationContext
234
235convertToApplicationContext(sendableContext: SendableContext): common.ApplicationContext
236
237Converts a SendableContext object to an ApplicationContext object.
238
239**System capability**: SystemCapability.Ability.AbilityRuntime.Core
240
241**Atomic service API**: This API can be used in atomic services since API version 12.
242
243**Parameters**
244
245| Name| Type| Mandatory| Description|
246| ------- | ------- | ------- | ------- |
247| sendableContext | [SendableContext](js-apis-inner-application-sendableContext.md) | Yes| SendableContext object.|
248
249**Return value**
250
251| Type| Description|
252| -------- | -------- |
253| common.ApplicationContext | [ApplicationContext](js-apis-inner-application-applicationContext.md) object.|
254
255**Error codes**
256
257For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
258
259| ID| Error Message|
260| ------- | ------- |
261| 401     | If the input parameter invalid. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
262
263**Example**
264
265Context passed by the main thread:
266```ts
267import { AbilityConstant, UIAbility, Want, common, sendableContextManager } from '@kit.AbilityKit';
268import { hilog } from '@kit.PerformanceAnalysisKit';
269import { worker } from '@kit.ArkTS';
270
271@Sendable
272export class SendableObject {
273  constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
274    this.sendableContext = sendableContext;
275    this.contextName = contextName;
276  }
277
278  sendableContext: sendableContextManager.SendableContext;
279  contextName: string;
280}
281
282export default class EntryAbility extends UIAbility {
283  worker: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
284
285  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
286    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
287
288    // convert and post
289    try {
290      let context: common.Context = this.context as common.Context;
291      let applicationContext = context.getApplicationContext();
292      let sendableContext: sendableContextManager.SendableContext = sendableContextManager.convertFromContext(applicationContext);
293      let object: SendableObject = new SendableObject(sendableContext, 'ApplicationContext');
294      hilog.info(0x0000, 'testTag', '%{public}s', 'Ability post message');
295      this.worker.postMessageWithSharedSendable(object);
296    } catch (error) {
297      hilog.error(0x0000, 'testTag', 'convertFromContext failed %{public}s', JSON.stringify(error));
298    }
299  }
300}
301```
302
303Context received by the Worker thread:
304```ts
305import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
306import { common, sendableContextManager } from '@kit.AbilityKit';
307import { hilog } from '@kit.PerformanceAnalysisKit';
308
309@Sendable
310export class SendableObject {
311  constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
312    this.sendableContext = sendableContext;
313    this.contextName = contextName;
314  }
315
316  sendableContext: sendableContextManager.SendableContext;
317  contextName: string;
318}
319
320const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
321
322workerPort.onmessage = (e: MessageEvents) => {
323  let object: SendableObject = e.data;
324  let sendableContext: sendableContextManager.SendableContext = object.sendableContext;
325  if (object.contextName == 'ApplicationContext') {
326    hilog.info(0x0000, 'testTag', '%{public}s', 'convert to application context.');
327    try {
328      let context: common.ApplicationContext = sendableContextManager.convertToApplicationContext(sendableContext);
329      // Obtain the sandbox path after obtaining the Context object.
330      hilog.info(0x0000, 'testTag', 'worker context.databaseDir: %{public}s', context.databaseDir);
331    } catch (error) {
332      hilog.error(0x0000, 'testTag', 'convertToApplicationContext failed %{public}s', JSON.stringify(error));
333    }
334  }
335}
336
337workerPort.onmessageerror = (e: MessageEvents) => {
338  hilog.info(0x0000, 'testTag', '%{public}s', 'onmessageerror');
339}
340
341workerPort.onerror = (e: ErrorEvent) => {
342  hilog.info(0x0000, 'testTag', '%{public}s', 'onerror');
343}
344```
345
346## sendableContextManager.convertToAbilityStageContext
347
348convertToAbilityStageContext(sendableContext: SendableContext): common.AbilityStageContext
349
350Converts a SendableContext object to an AbilityStageContext object.
351
352**System capability**: SystemCapability.Ability.AbilityRuntime.Core
353
354**Atomic service API**: This API can be used in atomic services since API version 12.
355
356**Parameters**
357
358| Name| Type| Mandatory| Description|
359| ------- | ------- | ------- | ------- |
360| sendableContext | [SendableContext](js-apis-inner-application-sendableContext.md) | Yes| SendableContext object.|
361
362**Return value**
363
364| Type| Description|
365| -------- | -------- |
366| common.AbilityStageContext | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) object.|
367
368**Error codes**
369
370For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
371
372| ID| Error Message|
373| ------- | ------- |
374| 401     | If the input parameter invalid. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
375
376**Example**
377
378Context passed by the main thread:
379```ts
380import { UIAbility, sendableContextManager } from '@kit.AbilityKit';
381import { hilog } from '@kit.PerformanceAnalysisKit';
382import { worker } from '@kit.ArkTS';
383
384@Sendable
385export class SendableObject {
386  constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
387    this.sendableContext = sendableContext;
388    this.contextName = contextName;
389  }
390
391  sendableContext: sendableContextManager.SendableContext;
392  contextName: string;
393}
394
395export default class EntryAbility extends UIAbility {
396  worker: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
397
398  onCreate(): void {
399    hilog.info(0x0000, 'testTag', '%{public}s', 'AbilityStage onCreate');
400
401    // convert and post
402    try {
403      let sendableContext: sendableContextManager.SendableContext = sendableContextManager.convertFromContext(this.context);
404      let object: SendableObject = new SendableObject(sendableContext, 'AbilityStageContext');
405      hilog.info(0x0000, 'testTag', '%{public}s', 'AbilityStage post message');
406      this.worker.postMessageWithSharedSendable(object);
407    } catch (error) {
408      hilog.error(0x0000, 'testTag', 'convertFromContext failed %{public}s', JSON.stringify(error));
409    }
410  }
411}
412```
413
414Context received by the Worker thread:
415```ts
416import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
417import { common, sendableContextManager } from '@kit.AbilityKit';
418import { hilog } from '@kit.PerformanceAnalysisKit';
419
420@Sendable
421export class SendableObject {
422  constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
423    this.sendableContext = sendableContext;
424    this.contextName = contextName;
425  }
426
427  sendableContext: sendableContextManager.SendableContext;
428  contextName: string;
429}
430
431const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
432
433workerPort.onmessage = (e: MessageEvents) => {
434  let object: SendableObject = e.data;
435  let sendableContext: sendableContextManager.SendableContext = object.sendableContext;
436  if (object.contextName == 'AbilityStageContext') {
437    hilog.info(0x0000, 'testTag', '%{public}s', 'convert to abilitystage context.');
438    try {
439      let context: common.AbilityStageContext = sendableContextManager.convertToAbilityStageContext(sendableContext);
440      // Obtain the sandbox path after obtaining the Context object.
441      hilog.info(0x0000, 'testTag', 'worker context.databaseDir: %{public}s', context.databaseDir);
442    } catch (error) {
443      hilog.error(0x0000, 'testTag', 'convertToAbilityStageContext failed %{public}s', JSON.stringify(error));
444    }
445  }
446}
447
448workerPort.onmessageerror = (e: MessageEvents) => {
449  hilog.info(0x0000, 'testTag', '%{public}s', 'onmessageerror');
450}
451
452workerPort.onerror = (e: ErrorEvent) => {
453  hilog.info(0x0000, 'testTag', '%{public}s', 'onerror');
454}
455```
456
457## sendableContextManager.convertToUIAbilityContext
458
459convertToUIAbilityContext(sendableContext: SendableContext): common.UIAbilityContext
460
461Converts a SendableContext object to a UIAbilityContext object.
462
463**System capability**: SystemCapability.Ability.AbilityRuntime.Core
464
465**Atomic service API**: This API can be used in atomic services since API version 12.
466
467**Parameters**
468
469| Name| Type| Mandatory| Description|
470| ------- | ------- | ------- | ------- |
471| sendableContext | [SendableContext](js-apis-inner-application-sendableContext.md) | Yes| SendableContext object.|
472
473**Return value**
474
475| Type| Description|
476| -------- | -------- |
477| common.UIAbilityContext | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) object.|
478
479**Error codes**
480
481For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
482
483| ID| Error Message|
484| ------- | ------- |
485| 401     | If the input parameter invalid. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
486
487**Example**
488
489Context passed by the main thread:
490```ts
491import { AbilityConstant, UIAbility, Want, common, sendableContextManager } from '@kit.AbilityKit';
492import { hilog } from '@kit.PerformanceAnalysisKit';
493import { worker } from '@kit.ArkTS';
494
495@Sendable
496export class SendableObject {
497  constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
498    this.sendableContext = sendableContext;
499    this.contextName = contextName;
500  }
501
502  sendableContext: sendableContextManager.SendableContext;
503  contextName: string;
504}
505
506export default class EntryAbility extends UIAbility {
507  worker: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
508
509  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
510    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
511
512    // convert and post
513    try {
514      let sendableContext: sendableContextManager.SendableContext = sendableContextManager.convertFromContext(this.context);
515      let object: SendableObject = new SendableObject(sendableContext, 'EntryAbilityContext');
516      hilog.info(0x0000, 'testTag', '%{public}s', 'Ability post message');
517      this.worker.postMessageWithSharedSendable(object);
518    } catch (error) {
519      hilog.error(0x0000, 'testTag', 'convertFromContext failed %{public}s', JSON.stringify(error));
520    }
521  }
522}
523```
524
525Context received by the Worker thread:
526```ts
527import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
528import { common, sendableContextManager } from '@kit.AbilityKit';
529import { hilog } from '@kit.PerformanceAnalysisKit';
530
531@Sendable
532export class SendableObject {
533  constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
534    this.sendableContext = sendableContext;
535    this.contextName = contextName;
536  }
537
538  sendableContext: sendableContextManager.SendableContext;
539  contextName: string;
540}
541
542const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
543
544workerPort.onmessage = (e: MessageEvents) => {
545  let object: SendableObject = e.data;
546  let sendableContext: sendableContextManager.SendableContext = object.sendableContext;
547  if (object.contextName == 'EntryAbilityContext') {
548    hilog.info(0x0000, 'testTag', '%{public}s', 'convert to uiability context.');
549    try {
550      let context: common.UIAbilityContext = sendableContextManager.convertToUIAbilityContext(sendableContext);
551      // Obtain the sandbox path after obtaining the Context object.
552      hilog.info(0x0000, 'testTag', 'worker context.databaseDir: %{public}s', context.databaseDir);
553    } catch (error) {
554      hilog.error(0x0000, 'testTag', 'convertToUIAbilityContext failed %{public}s', JSON.stringify(error));
555    }
556  }
557}
558
559workerPort.onmessageerror = (e: MessageEvents) => {
560  hilog.info(0x0000, 'testTag', '%{public}s', 'onmessageerror');
561}
562
563workerPort.onerror = (e: ErrorEvent) => {
564  hilog.info(0x0000, 'testTag', '%{public}s', 'onerror');
565}
566```
567## sendableContextManager.setEventHubMultithreadingEnabled<sup>20+<sup>
568
569setEventHubMultithreadingEnabled(context: common.Context, enabled: boolean): void
570
571Enables the cross-thread data transfer feature of [EventHub](./js-apis-inner-application-eventHub.md) in a [Context](js-apis-inner-application-context.md) object.
572
573> **NOTE**
574>
575> - When multiple Context objects communicate, you need to call this API to set each Context object to support EventHub cross-thread data transfer.
576> - Before this API is called, data is passed by reference. After this API is called, data is passed through serialization, which means that the data of the sender thread is independent of that of the receiver thread.
577
578**System capability**: SystemCapability.Ability.AbilityRuntime.Core
579
580**Atomic service API**: This API can be used in atomic services since API version 20.
581
582**Parameters**
583
584| Name | Type          | Mandatory| Description                                                        |
585| ------- | -------------- | ---- | ------------------------------------------------------------ |
586| context | [common.Context](js-apis-inner-application-context.md) | Yes  | Context object. For details about the serialization data types supported by Eventhub, see [Sequenceable Data Types](../apis-arkts/js-apis-taskpool.md#sequenceable-data-types). The data size cannot exceed 16 MB.|
587| enabled  | boolean        | Yes  | Whether to enable the cross-thread data transfer feature. **true** to enable, **false** otherwise.                               |
588
589**Example**
590
591Enable the cross-thread data transfer feature of [EventHub](./js-apis-inner-application-eventHub.md) in a [Context](./js-apis-inner-application-context.md) object in the main thread, convert the Context object to a [SenableContext](js-apis-inner-application-sendableContext.md) object, and send the SendableContext object to the [Worker](../apis-arkts/js-apis-worker.md) thread.
592
593```ts
594import { common, sendableContextManager } from '@kit.AbilityKit';
595import { worker } from '@kit.ArkTS';
596import { hilog } from '@kit.PerformanceAnalysisKit';
597
598const DOMAIN = 0x0000;
599
600@Sendable
601export class SendableObject {
602  constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
603    this.sendableContext = sendableContext;
604    this.contextName = contextName;
605  }
606
607  sendableContext: sendableContextManager.SendableContext;
608  contextName: string;
609}
610
611@Entry
612@Component
613struct Index {
614  @State context: common.Context | undefined = this.getUIContext().getHostContext();
615  worker1: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
616
617  aboutToAppear(): void {
618    let context: common.Context = this.context as common.Context;
619    context.eventHub.on('event1', this.eventFunc);
620    context.eventHub.emit('event1', 'xingming', 22);
621  }
622
623  eventFunc(name: string, age: number) {
624    hilog.info(DOMAIN, 'testTag', 'name %{public}s age %{public}d', name, age);
625  }
626
627  build() {
628    Column() {
629      Row() {
630        Button('thread 1')
631          .size({ width: 100, height: 100 })
632          .onClick(() => {
633            if (this.context == undefined) {
634              return;
635            }
636            sendableContextManager.setEventHubMultithreadingEnabled(this.context, true);
637            let sendableContext: sendableContextManager.SendableContext =
638              sendableContextManager.convertFromContext(this.context);
639            let object: SendableObject = new SendableObject(sendableContext, 'BaseContext');
640            this.worker1.postMessageWithSharedSendable(object);
641          })
642      }
643    }
644  }
645}
646```
647
648After receiving the [SendableContext](js-apis-inner-application-sendableContext.md) object in the [Worker](../apis-arkts/js-apis-worker.md) thread, convert it to a [Context](./js-apis-inner-application-context.md) object. Then, enable the cross-thread data transfer feature of [EventHub](./js-apis-inner-application-eventHub.md) in the Context object in the Worker thread, and send a message back to the main thread using this feature.
649
650```ts
651import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
652import { common, sendableContextManager } from '@kit.AbilityKit';
653import { hilog } from '@kit.PerformanceAnalysisKit';
654
655const DOMAIN = 0x0000;
656
657@Sendable
658export class SendableObject {
659  constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
660    this.sendableContext = sendableContext;
661    this.contextName = contextName;
662  }
663
664  sendableContext: sendableContextManager.SendableContext;
665  contextName: string;
666}
667
668const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
669
670workerPort.onmessage = (e: MessageEvents) => {
671  let object: SendableObject = e.data;
672  let sendableContext: sendableContextManager.SendableContext = object.sendableContext;
673  if (object.contextName == 'BaseContext') {
674    let context: common.Context = sendableContextManager.convertToContext(sendableContext);
675    sendableContextManager.setEventHubMultithreadingEnabled(context, true);
676    context.eventHub.emit('event1', 'xingming', 40);
677  }
678};
679
680workerPort.onmessageerror = (e: MessageEvents) => {
681  hilog.error(DOMAIN, 'testTag', '%{public}s', 'onmessageerror');
682};
683
684workerPort.onerror = (e: ErrorEvent) => {
685  hilog.error(DOMAIN, 'testTag', '%{public}s', 'onerror');
686};
687```
688