The sendableContextManager module provides APIs for converting between Context and SendableContext objects.
This module is used to transfer data between concurrent ArkTS instances (including the main thread and the worker thread of TaskPool or Worker).
When the main thread transfers sendable data (data that complies with the Sendable protocol) to the child thread (such as the TaskPool or Worker thread), the conversion between the Context and SendableContext is required. The process is as follows:
The Context here is different from that created by createModuleContext. The differences are as follows:
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 to transfer data across instances, call setEventHubMultithreadingEnabled to enable the cross-thread data transfer feature.
Context created using createModuleContext: ArkTS concurrent instances hold different application-side Context objects that correspond to different underlying Context objects.
The Context types used in the conversion must be the same. For example, if the main thread uses convertFromContext to convert the UIAbilityContext to the SendableContext, the child thread must call convertToUIAbilityContext to convert the received SendableContext to the UIAbilityContext.
Currently, the following types of Context support conversion: Context, ApplicationContext, AbilityStageContext, and UIAbilityContext.
type SendableContext = _SendableContext
Defines the Sendable context. It complies with the Sendable protocol and inherits from lang.ISendable.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Atomic service API: This API can be used in atomic services since API version 12.
| Type | Description |
|---|---|
| _SendableContext | 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). |
convertFromContext(context: common.Context): SendableContext
Converts a Context object to a SendableContext object.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| context | common.Context | Yes | Context object. The Context base class, and its child classes ApplicationContext, AbilityStageContext, and UIAbilityContext are supported. |
Return value
| Type | Description |
|---|---|
| SendableContext | SendableContext object. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | If the input parameter invalid. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
Example
import { AbilityConstant, UIAbility, Want, sendableContextManager } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { worker } from '@kit.ArkTS';
@Sendable
export class SendableObject {
constructor(sendableContext: sendableContextManager.SendableContext) {
this.sendableContext = sendableContext;
}
sendableContext: sendableContextManager.SendableContext;
// other sendable object
}
export default class EntryAbility extends UIAbility {
worker: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
// convert and post
try {
let sendableContext: sendableContextManager.SendableContext =
sendableContextManager.convertFromContext(this.context);
let object: SendableObject = new SendableObject(sendableContext);
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability post message');
this.worker.postMessageWithSharedSendable(object);
} catch (error) {
hilog.error(0x0000, 'testTag', 'convertFromContext failed %{public}s', JSON.stringify(error));
}
}
} convertToContext(sendableContext: SendableContext): common.Context
Converts a SendableContext object to a Context object.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| sendableContext | SendableContext | Yes | SendableContext object. |
Return value
| Type | Description |
|---|---|
| common.Context | Context object. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | If the input parameter invalid. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
Example
Context passed by the main thread:
import { AbilityConstant, UIAbility, Want, common, sendableContextManager } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { worker } from '@kit.ArkTS';
@Sendable
export class SendableObject {
constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
this.sendableContext = sendableContext;
this.contextName = contextName;
}
sendableContext: sendableContextManager.SendableContext;
contextName: string;
}
export default class EntryAbility extends UIAbility {
worker: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
// convert and post
try {
let context: common.Context = this.context as common.Context;
let sendableContext: sendableContextManager.SendableContext = sendableContextManager.convertFromContext(context);
let object: SendableObject = new SendableObject(sendableContext, 'BaseContext');
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability post message');
this.worker.postMessageWithSharedSendable(object);
} catch (error) {
hilog.error(0x0000, 'testTag', 'convertFromContext failed %{public}s', JSON.stringify(error));
}
}
} Context received by the Worker thread:
import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
import { common, sendableContextManager } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
@Sendable
export class SendableObject {
constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
this.sendableContext = sendableContext;
this.contextName = contextName;
}
sendableContext: sendableContextManager.SendableContext;
contextName: string;
}
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
workerPort.onmessage = (e: MessageEvents) => {
let object: SendableObject = e.data;
let sendableContext: sendableContextManager.SendableContext = object.sendableContext;
if (object.contextName == 'BaseContext') {
hilog.info(0x0000, 'testTag', '%{public}s', 'convert to context.');
try {
let context: common.Context = sendableContextManager.convertToContext(sendableContext);
// Obtain the sandbox path after obtaining the Context object.
hilog.info(0x0000, 'testTag', 'worker context.databaseDir: %{public}s', context.databaseDir);
} catch (error) {
hilog.error(0x0000, 'testTag', 'convertToContext failed %{public}s', JSON.stringify(error));
}
}
}
workerPort.onmessageerror = (e: MessageEvents) => {
hilog.info(0x0000, 'testTag', '%{public}s', 'onmessageerror');
}
workerPort.onerror = (e: ErrorEvent) => {
hilog.info(0x0000, 'testTag', '%{public}s', 'onerror');
} convertToApplicationContext(sendableContext: SendableContext): common.ApplicationContext
Converts a SendableContext object to an ApplicationContext object.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| sendableContext | SendableContext | Yes | SendableContext object. |
Return value
| Type | Description |
|---|---|
| common.ApplicationContext | ApplicationContext object. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | If the input parameter invalid. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
Example
Context passed by the main thread:
import { AbilityConstant, UIAbility, Want, common, sendableContextManager } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { worker } from '@kit.ArkTS';
@Sendable
export class SendableObject {
constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
this.sendableContext = sendableContext;
this.contextName = contextName;
}
sendableContext: sendableContextManager.SendableContext;
contextName: string;
}
export default class EntryAbility extends UIAbility {
worker: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
// convert and post
try {
let context: common.Context = this.context as common.Context;
let applicationContext = context.getApplicationContext();
let sendableContext: sendableContextManager.SendableContext =
sendableContextManager.convertFromContext(applicationContext);
let object: SendableObject = new SendableObject(sendableContext, 'ApplicationContext');
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability post message');
this.worker.postMessageWithSharedSendable(object);
} catch (error) {
hilog.error(0x0000, 'testTag', 'convertFromContext failed %{public}s', JSON.stringify(error));
}
}
} Context received by the Worker thread:
import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
import { common, sendableContextManager } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
@Sendable
export class SendableObject {
constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
this.sendableContext = sendableContext;
this.contextName = contextName;
}
sendableContext: sendableContextManager.SendableContext;
contextName: string;
}
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
workerPort.onmessage = (e: MessageEvents) => {
let object: SendableObject = e.data;
let sendableContext: sendableContextManager.SendableContext = object.sendableContext;
if (object.contextName == 'ApplicationContext') {
hilog.info(0x0000, 'testTag', '%{public}s', 'convert to application context.');
try {
let context: common.ApplicationContext = sendableContextManager.convertToApplicationContext(sendableContext);
// Obtain the sandbox path after obtaining the Context object.
hilog.info(0x0000, 'testTag', 'worker context.databaseDir: %{public}s', context.databaseDir);
} catch (error) {
hilog.error(0x0000, 'testTag', 'convertToApplicationContext failed %{public}s', JSON.stringify(error));
}
}
}
workerPort.onmessageerror = (e: MessageEvents) => {
hilog.info(0x0000, 'testTag', '%{public}s', 'onmessageerror');
}
workerPort.onerror = (e: ErrorEvent) => {
hilog.info(0x0000, 'testTag', '%{public}s', 'onerror');
} convertToAbilityStageContext(sendableContext: SendableContext): common.AbilityStageContext
Converts a SendableContext object to an AbilityStageContext object.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| sendableContext | SendableContext | Yes | SendableContext object. |
Return value
| Type | Description |
|---|---|
| common.AbilityStageContext | AbilityStageContext object. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | If the input parameter invalid. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
Example
Context passed by the main thread:
import { UIAbility, sendableContextManager } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { worker } from '@kit.ArkTS';
@Sendable
export class SendableObject {
constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
this.sendableContext = sendableContext;
this.contextName = contextName;
}
sendableContext: sendableContextManager.SendableContext;
contextName: string;
}
export default class EntryAbility extends UIAbility {
worker: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
onCreate(): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'AbilityStage onCreate');
// convert and post
try {
let sendableContext: sendableContextManager.SendableContext =
sendableContextManager.convertFromContext(this.context);
let object: SendableObject = new SendableObject(sendableContext, 'AbilityStageContext');
hilog.info(0x0000, 'testTag', '%{public}s', 'AbilityStage post message');
this.worker.postMessageWithSharedSendable(object);
} catch (error) {
hilog.error(0x0000, 'testTag', 'convertFromContext failed %{public}s', JSON.stringify(error));
}
}
} Context received by the Worker thread:
import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
import { common, sendableContextManager } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
@Sendable
export class SendableObject {
constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
this.sendableContext = sendableContext;
this.contextName = contextName;
}
sendableContext: sendableContextManager.SendableContext;
contextName: string;
}
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
workerPort.onmessage = (e: MessageEvents) => {
let object: SendableObject = e.data;
let sendableContext: sendableContextManager.SendableContext = object.sendableContext;
if (object.contextName == 'AbilityStageContext') {
hilog.info(0x0000, 'testTag', '%{public}s', 'convert to abilitystage context.');
try {
let context: common.AbilityStageContext = sendableContextManager.convertToAbilityStageContext(sendableContext);
// Obtain the sandbox path after obtaining the Context object.
hilog.info(0x0000, 'testTag', 'worker context.databaseDir: %{public}s', context.databaseDir);
} catch (error) {
hilog.error(0x0000, 'testTag', 'convertToAbilityStageContext failed %{public}s', JSON.stringify(error));
}
}
}
workerPort.onmessageerror = (e: MessageEvents) => {
hilog.info(0x0000, 'testTag', '%{public}s', 'onmessageerror');
}
workerPort.onerror = (e: ErrorEvent) => {
hilog.info(0x0000, 'testTag', '%{public}s', 'onerror');
} convertToUIAbilityContext(sendableContext: SendableContext): common.UIAbilityContext
Converts a SendableContext object to a UIAbilityContext object.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| sendableContext | SendableContext | Yes | SendableContext object. |
Return value
| Type | Description |
|---|---|
| common.UIAbilityContext | UIAbilityContext object. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | If the input parameter invalid. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
Example
Context passed by the main thread:
import { AbilityConstant, UIAbility, Want, common, sendableContextManager } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { worker } from '@kit.ArkTS';
@Sendable
export class SendableObject {
constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
this.sendableContext = sendableContext;
this.contextName = contextName;
}
sendableContext: sendableContextManager.SendableContext;
contextName: string;
}
export default class EntryAbility extends UIAbility {
worker: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
// convert and post
try {
let sendableContext: sendableContextManager.SendableContext =
sendableContextManager.convertFromContext(this.context);
let object: SendableObject = new SendableObject(sendableContext, 'EntryAbilityContext');
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability post message');
this.worker.postMessageWithSharedSendable(object);
} catch (error) {
hilog.error(0x0000, 'testTag', 'convertFromContext failed %{public}s', JSON.stringify(error));
}
}
} Context received by the Worker thread:
import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
import { common, sendableContextManager } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
@Sendable
export class SendableObject {
constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
this.sendableContext = sendableContext;
this.contextName = contextName;
}
sendableContext: sendableContextManager.SendableContext;
contextName: string;
}
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
workerPort.onmessage = (e: MessageEvents) => {
let object: SendableObject = e.data;
let sendableContext: sendableContextManager.SendableContext = object.sendableContext;
if (object.contextName == 'EntryAbilityContext') {
hilog.info(0x0000, 'testTag', '%{public}s', 'convert to UIAbility context.');
try {
let context: common.UIAbilityContext = sendableContextManager.convertToUIAbilityContext(sendableContext);
// Obtain the sandbox path after obtaining the Context object.
hilog.info(0x0000, 'testTag', 'worker context.databaseDir: %{public}s', context.databaseDir);
} catch (error) {
hilog.error(0x0000, 'testTag', 'convertToUIAbilityContext failed %{public}s', JSON.stringify(error));
}
}
}
workerPort.onmessageerror = (e: MessageEvents) => {
hilog.info(0x0000, 'testTag', '%{public}s', 'onmessageerror');
}
workerPort.onerror = (e: ErrorEvent) => {
hilog.info(0x0000, 'testTag', '%{public}s', 'onerror');
} setEventHubMultithreadingEnabled(context: common.Context, enabled: boolean): void
Enables the cross-thread data transfer feature of EventHub in Context.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| context | common.Context | Yes | Context object. For details about the serialization data types supported by Eventhub, see Sequenceable Data Types. The data size cannot exceed 16 MB. |
| enabled | boolean | Yes | Whether to enable the cross-thread data transfer feature. - true: The cross-thread data transfer feature is enabled, and data is passed by reference. - false: The cross-thread data transfer feature is disabled. Data is passed through serialization, which means that the data of the sender thread is independent of that of the receiver thread. |
Example
Enable the cross-thread data transfer feature of EventHub in a Context object on the main thread, convert the Context object to a SendableContext object, and send the SendableContext object to the Worker thread.
import { common, sendableContextManager } from '@kit.AbilityKit';
import { worker } from '@kit.ArkTS';
import { hilog } from '@kit.PerformanceAnalysisKit';
const DOMAIN = 0x0000;
@Sendable
export class SendableObject {
constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
this.sendableContext = sendableContext;
this.contextName = contextName;
}
sendableContext: sendableContextManager.SendableContext;
contextName: string;
}
@Entry
@Component
struct Index {
@State context: common.Context | undefined = this.getUIContext().getHostContext();
worker1: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
aboutToAppear(): void {
let context: common.Context = this.context as common.Context;
context.eventHub.on('event1', this.eventFunc);
context.eventHub.emit('event1', 'xingming', 22);
}
eventFunc(name: string, age: number) {
hilog.info(DOMAIN, 'testTag', 'name %{public}s age %{public}d', name, age);
}
build() {
Column() {
Row() {
Button('thread 1')
.size({ width: 100, height: 100 })
.onClick(() => {
if (this.context == undefined) {
return;
}
sendableContextManager.setEventHubMultithreadingEnabled(this.context, true);
let sendableContext: sendableContextManager.SendableContext =
sendableContextManager.convertFromContext(this.context);
let object: SendableObject = new SendableObject(sendableContext, 'BaseContext');
this.worker1.postMessageWithSharedSendable(object);
})
}
}
}
} After receiving the SendableContext object on the Worker thread, convert it to a Context object. Then, enable the cross-thread data transfer feature of EventHub in the Context object on the Worker thread, and send a message back to the main thread using this feature.
import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
import { common, sendableContextManager } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
const DOMAIN = 0x0000;
@Sendable
export class SendableObject {
constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
this.sendableContext = sendableContext;
this.contextName = contextName;
}
sendableContext: sendableContextManager.SendableContext;
contextName: string;
}
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
workerPort.onmessage = (e: MessageEvents) => {
let object: SendableObject = e.data;
let sendableContext: sendableContextManager.SendableContext = object.sendableContext;
if (object.contextName == 'BaseContext') {
let context: common.Context = sendableContextManager.convertToContext(sendableContext);
sendableContextManager.setEventHubMultithreadingEnabled(context, true);
context.eventHub.emit('event1', 'xingming', 40);
}
};
workerPort.onmessageerror = (e: MessageEvents) => {
hilog.error(DOMAIN, 'testTag', '%{public}s', 'onmessageerror');
};
workerPort.onerror = (e: ErrorEvent) => {
hilog.error(DOMAIN, 'testTag', '%{public}s', 'onerror');
};