source
stringlengths
14
113
code
stringlengths
10
21.3k
application-dev\arkts-utils\long-time-task-guide.md
// Index.ets import { sensor } from '@kit.SensorServiceKit'; import { taskpool } from '@kit.ArkTS'; import { BusinessError, emitter } from '@kit.BasicServicesKit';
application-dev\arkts-utils\long-time-task-guide.md
// Index.ets @Concurrent async function SensorListener() : Promise<void> { sensor.on(sensor.SensorId.ACCELEROMETER, (data) => { emitter.emit({ eventId: 0 }, { data: data }); }, { interval: 1000000000 }); emitter.on({ eventId: 1 }, () => { sensor.off(sensor.SensorId.ACCELEROMETER) emitter.off(1) }) }
application-dev\arkts-utils\long-time-task-guide.md
// Index.ets @Entry @Component struct Index { sensorTask?: taskpool.LongTask build() { Column() { Text("Add listener") .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { this.sensorTask = new taskpool.LongTask(SensorListener); emitter.on({ eventId: 0 }, (data) => { // Do something here console.info(`Receive ACCELEROMETER data: {${data.data?.x}, ${data.data?.y}, ${data.data?.z}`); }); taskpool.execute(this.sensorTask).then(() => { console.info("Add listener of ACCELEROMETER success"); }).catch((e: BusinessError) => { // Process error }) }) Text("Delete listener") .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { emitter.emit({ eventId: 1 }); emitter.off(0); if(this.sensorTask != undefined) { taskpool.terminateTask(this.sensorTask); } else { console.error("sensorTask is undefined."); } }) } .height('100%') .width('100%') } }
application-dev\arkts-utils\makeobserved-sendable.md
// SendableData.ets @Sendable export class SendableData { name: string = 'Tom'; age: number = 20; gender: number = 1; likes: number = 1; follow: boolean = false; }
application-dev\arkts-utils\makeobserved-sendable.md
import { taskpool } from '@kit.ArkTS'; import { SendableData } from './SendableData'; import { UIUtils } from '@kit.ArkUI'; @Concurrent function threadGetData(param: string): SendableData { // Process data in the child thread. let ret = new SendableData(); console.info(`Concurrent threadGetData, param ${param}`); ret.name = param + "-o"; ret.age = Math.floor(Math.random() * 40); ret.likes = Math.floor(Math.random() * 100); return ret; } @Entry @ComponentV2 struct Index { // Use makeObserved to add observation to a regular object or a @Sendable object. @Local send: SendableData = UIUtils.makeObserved(new SendableData()); build() { Column() { Text(this.send.name) Button("change name").onClick(() => { // Changes to properties are observable. this.send.name += "0"; }) Button("task").onClick(() => { // Enqueue the function to be executed in the task pool, waiting to be dispatched to a worker thread. // Data construction and processing can be done in the child thread, but observable data cannot be passed to the child thread (observable data can only be manipulated in the UI main thread). // Therefore, only the 'name' property of 'this.send' is passed to the child thread. taskpool.execute(threadGetData, this.send.name).then(val => { // Used together with @Local to observe changes to 'this.send'. this.send = UIUtils.makeObserved(val as SendableData); }) }) } } }
application-dev\arkts-utils\multi-thread-cancel-task.md
// Mock.ets @Sendable export class SendableTest { // Store the task ID. private taskId: number = 0; constructor(id: number) { this.taskId = id; } public getTaskId(): number { return this.taskId; } }
application-dev\arkts-utils\multi-thread-cancel-task.md
// Index.ets import { taskpool } from '@kit.ArkTS'; import { SendableTest } from './Mock' @Concurrent function cancel(send: SendableTest) { console.info("cancel task finished"); // Cancel the task in the child thread based on the task ID. taskpool.cancel(send.getTaskId()); } @Concurrent function delayed() { console.info("delayed task finished"); } @Entry @Component struct Index { @State message: string = 'Hello World!'; @State books: string[] = []; build() { Column({ space: 1 }) { Button(this.books[3]) .fontSize(20) .padding(10) .fontWeight(FontWeight.Bold) .onClick(async () => { let task = new taskpool.Task(delayed); taskpool.executeDelayed(2000, task).catch((e: BusinessError) => { console.error(`taskpool execute error, message is: ${e.message}`); // taskpool execute error, message is: taskpool:: task has been canceled }); let send = new SendableTest(task.taskId); taskpool.execute(cancel, send); }) } .height('100%') .width('100%') } }
application-dev\arkts-utils\multi-thread-concurrency-overview.md
// The pseudocode is used here to help you understand the differences between the shared memory model and the actor model. class Queue { // ... push(value: number) { } empty(): boolean { // ... return true; } pop(value: number): number { // ... return value; } } class Mutex { // ... lock(): boolean { // ... return true; } unlock() { } } class BufferQueue { queue: Queue = new Queue(); mutex: Mutex = new Mutex(); add(value: number) { // Attempt to acquire the lock. if (this.mutex.lock()) { this.queue.push(value); this.mutex.unlock(); } } take(value: number): number { let res: number = 0; // Attempt to acquire the lock. if (this.mutex.lock()) { if (this.queue.empty()) { res = 1; return res; } let num: number = this.queue.pop(value); this.mutex.unlock(); res = num; } return res; } } // Construct a globally shared memory buffer. let g_bufferQueue = new BufferQueue(); class Producer { constructor() { } run() { let value = Math.random(); // Access to the bufferQueue object across threads. g_bufferQueue.add(value); } } class ConsumerTest { constructor() { } run() { // Access to the bufferQueue object across threads. let num = 123; let res = g_bufferQueue.take(num); if (res != null) { // Add consumption logic here. } } } function Main(): void { let consumer: ConsumerTest = new ConsumerTest(); let producer1: Producer = new Producer(); for (let i = 0; i < 0; i++) { // Simulate the startup of multiple threads to execute a production task. // let thread = new Thread(); // thread.run(producer.run()); // consumer.run(); } }
application-dev\arkts-utils\multi-thread-concurrency-overview.md
import { taskpool } from '@kit.ArkTS'; // Cross-thread concurrent tasks @Concurrent async function produce(): Promise<number> { // Add production logic here. console.info('producing...'); return Math.random(); } class Consumer { public consume(value: Object) { // Add consumption logic here. console.info('consuming value: ' + value); } } @Entry @Component struct Index { @State message: string = 'Hello World'; build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) Button() { Text('start') }.onClick(() => { let produceTask: taskpool.Task = new taskpool.Task(produce); let consumer: Consumer = new Consumer(); for (let index: number = 0; index < 10; index++) { // Execute the asynchronous concurrent production task. taskpool.execute(produceTask).then((res: Object) => { consumer.consume(res); }).catch((e: Error) => { console.error(e.message); }) } }) .width('20%') .height('20%') } .width('100%') } .height('100%') } }
application-dev\arkts-utils\multi-thread-concurrency-overview.md
import { taskpool } from '@kit.ArkTS'; // Cross-thread concurrent tasks @Concurrent async function produce(): Promise<number> { // Add production logic here. console.info('producing...'); return Math.random(); } class Consumer { public consume(value: Object) { // Add consumption logic here. console.info('consuming value: ' + value); } } @Entry @Component struct Index { @State message: string = 'Hello World' build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) Button() { Text('start') }.onClick(async () => { let dataArray = new Array<number>(); let produceTask: taskpool.Task = new taskpool.Task(produce); let consumer: Consumer = new Consumer(); for (let index: number = 0; index < 10; index++) { // Execute the asynchronous concurrent production task. let result = await taskpool.execute(produceTask) as number; dataArray.push(result); } for (let index: number = 0; index < dataArray.length; index++) { consumer.consume(dataArray[index]); } }) .width('20%') .height('20%') } .width('100%') } .height('100%') } }
application-dev\arkts-utils\multi-time-consuming-tasks.md
// IconItemSource.ets export class IconItemSource { image: string | Resource = ''; text: string | Resource = ''; constructor(image: string | Resource = '', text: string | Resource = '') { this.image = image; this.text = text; } }
application-dev\arkts-utils\multi-time-consuming-tasks.md
// IndependentTask.ets import { IconItemSource } from './IconItemSource'; // Methods executed in the TaskPool thread must be decorated by @Concurrent. Otherwise, they cannot be called. @Concurrent export function loadPicture(count: number): IconItemSource[] { let iconItemSourceList: IconItemSource[] = []; // Add six IconItem data records. for (let index = 0; index < count; index++) { const numStart: number = index * 6; // Use six images in the loop. iconItemSourceList.push(new IconItemSource('$media:startIcon', `item${numStart + 1}`)); iconItemSourceList.push(new IconItemSource('$media:background', `item${numStart + 2}`)); iconItemSourceList.push(new IconItemSource('$media:foreground', `item${numStart + 3}`)); iconItemSourceList.push(new IconItemSource('$media:startIcon', `item${numStart + 4}`)); iconItemSourceList.push(new IconItemSource('$media:background', `item${numStart + 5}`)); iconItemSourceList.push(new IconItemSource('$media:foreground', `item${numStart + 6}`)); } return iconItemSourceList; }
application-dev\arkts-utils\multi-time-consuming-tasks.md
// MultiTask.ets import { taskpool } from '@kit.ArkTS'; import { IconItemSource } from './IconItemSource'; import { loadPicture } from './IndependentTask'; let iconItemSourceList: IconItemSource[][]; let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup(); taskGroup.addTask(new taskpool.Task(loadPicture, 30)); taskGroup.addTask(new taskpool.Task(loadPicture, 20)); taskGroup.addTask(new taskpool.Task(loadPicture, 10)); taskpool.execute(taskGroup).then((ret: object) => { let tmpLength = (ret as IconItemSource[][]).length for (let i = 0; i < tmpLength; i++) { for (let j = 0; j < ret[i].length; j++) { iconItemSourceList.push(ret[i][j]); } } })
application-dev\arkts-utils\napi-coerce-to-native-binding-object.md
// Index.d.ts export const getAddress: () => number; export const getSetSize: () => number; export const store: (a: number) => void; export const erase: (a: number) => void; export const clear: () => void; export const setTransferDetached: (b : boolean) => number;
application-dev\arkts-utils\napi-coerce-to-native-binding-object.md
import testNapi from 'libentry.so'; import { taskpool } from '@kit.ArkTS'; @Concurrent function getAddress() { let address: number = testNapi.getAddress(); console.info("taskpool:: address is " + address); } @Concurrent function store(a:number, b:number, c:number) { let size:number = testNapi.getSetSize(); console.info("set size is " + size + " before store"); testNapi.store(a); testNapi.store(b); testNapi.store(c); size = testNapi.getSetSize(); console.info("set size is " + size + " after store"); } @Concurrent function erase(a:number) { let size:number = testNapi.getSetSize(); console.info("set size is " + size + " before erase"); testNapi.erase(a); size = testNapi.getSetSize(); console.info("set size is " + size + " after erase"); } @Concurrent function clear() { let size:number = testNapi.getSetSize(); console.info("set size is " + size + " before clear"); testNapi.clear(); size = testNapi.getSetSize(); console.info("set size is " + size + " after clear"); } // Transfer mode. async function test(): Promise<void> { // Set setTransferDetached to true to enable the transfer mode. testNapi.setTransferDetached(true); let address:number = testNapi.getAddress(); console.info("host thread address is " + address); let task1 = new taskpool.Task(getAddress, testNapi); await taskpool.execute(task1); let task2 = new taskpool.Task(store, 1, 2, 3); await taskpool.execute(task2); let task3 = new taskpool.Task(store, 4, 5, 6); await taskpool.execute(task3); // In transfer mode, after testNapi is transferred across threads, the main thread can no longer access the value of the native object. let size:number = testNapi.getSetSize(); // The output log is "host thread size is undefined". console.info("host thread size is " + size); let task4 = new taskpool.Task(erase, 3); await taskpool.execute(task4); let task5 = new taskpool.Task(erase, 5); await taskpool.execute(task5); let task6 = new taskpool.Task(clear); await taskpool.execute(task6); } @Entry @Component struct Index { @State message: string = 'Hello World'; build() { Row() { Column() { Text(this.message) .fontSize($r('app.float.page_text_font_size')) .fontWeight(FontWeight.Bold) .onClick(() => { test(); }) } .width('100%') } .height('100%') } }
application-dev\arkts-utils\napi-coerce-to-native-binding-object.md
import testNapi from 'libentry.so'; import { taskpool } from '@kit.ArkTS'; @Concurrent function getAddress() { let address: number = testNapi.getAddress(); console.info("taskpool:: address is " + address); } @Concurrent function store(a:number, b:number, c:number) { let size:number = testNapi.getSetSize(); console.info("set size is " + size + " before store"); testNapi.store(a); testNapi.store(b); testNapi.store(c); size = testNapi.getSetSize(); console.info("set size is " + size + " after store"); } @Concurrent function erase(a:number) { let size:number = testNapi.getSetSize(); console.info("set size is " + size + " before erase"); testNapi.erase(a); size = testNapi.getSetSize(); console.info("set size is " + size + " after erase"); } @Concurrent function clear() { let size:number = testNapi.getSetSize(); console.info("set size is " + size + " before clear"); testNapi.clear(); size = testNapi.getSetSize(); console.info("set size is " + size + " after clear"); } // Shared mode. async function test(): Promise<void> { let address:number = testNapi.getAddress(); console.info("host thread address is " + address); let task1 = new taskpool.Task(getAddress, testNapi); await taskpool.execute(task1); let task2 = new taskpool.Task(store, 1, 2, 3); await taskpool.execute(task2); let task3 = new taskpool.Task(store, 4, 5, 6); await taskpool.execute(task3); // In shared mode, after testNapi is transferred across threads, the main thread can continue to access the value of the native object. let size:number = testNapi.getSetSize(); // The output log is "host thread size is 6". console.info("host thread size is " + size); let task4 = new taskpool.Task(erase, 3); await taskpool.execute(task4); let task5 = new taskpool.Task(erase, 5); await taskpool.execute(task5); let task6 = new taskpool.Task(clear); await taskpool.execute(task6); } @Entry @Component struct Index { @State message: string = 'Hello World'; build() { Row() { Column() { Text(this.message) .fontSize($r('app.float.page_text_font_size')) .fontWeight(FontWeight.Bold) .onClick(() => { test(); }) } .width('100%') } .height('100%') } }
application-dev\arkts-utils\napi-define-sendable-object.md
// Index.d.ts @Sendable export class MyObject { constructor(arg: number); plusOne(): number; public get value(); public set value(newVal: number); }
application-dev\arkts-utils\napi-define-sendable-object.md
// Index.ets import { MyObject } from 'libentry.so'; import { taskpool } from '@kit.ArkTS'; @Concurrent async function Sum(object: MyObject) { object.value = 2000; let num = object.plusOne(); console.info("taskpool thread num is " + num); // taskpool thread num is 2001 return num; } @Entry @Component struct Index { @State message: string = 'Hello World'; build() { Row() { Column() { Text(this.message) .fontSize($r('app.float.page_text_font_size')) .fontWeight(FontWeight.Bold) .onClick( async () => { let object : MyObject = new MyObject(0); object.value = 1023; let num = object.plusOne(); console.info("host thread num1 is " + num); // host thread num1 is 1024 let task = new taskpool.Task(Sum, object); let result = await taskpool.execute(task); console.info("host thread result is " + result); // host thread result is 2001 console.info("host thread num2 is " + object.value); // host thread num2 is 2001 }) } .width('100%') } .height('100%') } }
application-dev\arkts-utils\native-interthread-shared.md
// SendableObjTest.ets @Sendable export class SendableObjTest { static newSendable() { return 1024; } }
application-dev\arkts-utils\native-interthread-shared.md
// SendableObjTest.ets @Sendable export class SendableObjTest { static newSendable() { return 1024; } }
application-dev\arkts-utils\native-interthread-shared.md
// Index.ets import { hilog } from '@kit.PerformanceAnalysisKit'; import testNapi from 'libentry.so'; import { SendableObjTest } from './SendableObjTest' @Entry @Component struct Index { @State message: string = 'Hello World'; build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { SendableObjTest.newSendable() hilog.info(0x0000, 'testTag', 'Test send Sendable begin'); testNapi.testSendSendable(); hilog.info(0x0000, 'testTag', 'Test send Sendable end'); }) } .width('100%') } .height('100%') } }
application-dev\arkts-utils\nonlinear-container.md
// HashMap import { HashMap } from '@kit.ArkTS'; // Import the HashMap module. let hashMap1: HashMap<string, number> = new HashMap(); hashMap1.set('a', 123); // Add an element with key 'a' and value 123. let hashMap2: HashMap<number, number> = new HashMap(); hashMap2.set(4, 123); // Add an element with key 4 and value 123. console.info(`result: ${hashMap2.hasKey(4)}`); // Check whether an element with key 4 exists. Output: result: true console.info(`result: ${hashMap1.get('a')}`); // Access an element with key 'a'. Output: result: 123 // TreeMap import { TreeMap } from '@kit.ArkTS'; // Import the TreeMap module. let treeMap: TreeMap<string, number> = new TreeMap(); treeMap.set('a', 123); // Add an element with key 'a' and value 123. treeMap.set('6', 356); // Add an element with key '6' and value 356. console.info(`result: ${treeMap.get('a')}`); // Access an element with key 'a'. Output: result: 123 console.info(`result: ${treeMap.getFirstKey()}`); // Access the first element. Output: result: 6 console.info(`result: ${treeMap.getLastKey()}`); // Access the last element. Output: result: a // LightWeightMap import { LightWeightMap } from '@kit.ArkTS'; // Import the LightWeightMap module. let lightWeightMap: LightWeightMap<string, number> = new LightWeightMap(); lightWeightMap.set('x', 123); // Add an element with key 'x' and value 123. lightWeightMap.set('8', 356); // Add an element with key '8' and value 356. console.info(`result: ${lightWeightMap.get('a')}`); // Access an element with key 'a'. Output: result: undefined console.info(`result: ${lightWeightMap.get('x')}`); // Obtain the value of the element with key 'x'. Output: result: 123 console.info(`result: ${lightWeightMap.getIndexOfKey('8')}`); // Obtain the index of the element with key '8'. Output: result: 0 // PlainArray import { PlainArray } from '@kit.ArkTS'; // Import the PlainArray module. let plainArray: PlainArray<string> = new PlainArray(); plainArray.add(1, 'sdd'); // Add an element with key 1 and value 'sdd'. plainArray.add(2, 'sff'); // Add an element with key 2 and value 'sff'. console.info(`result: ${plainArray.get(1)}`); // Obtain the value of the element with key 1. Output: result: sdd console.info(`result: ${plainArray.getKeyAt(1)}`); // Obtain the key of the element at index 1. Output: result: 2
application-dev\arkts-utils\normal-object.md
// Test.ets // Custom class TestA. export class TestA { constructor(name: string) { this.name = name; } name: string = 'ClassA'; }
application-dev\arkts-utils\normal-object.md
// Index.ets import { taskpool } from '@kit.ArkTS'; import { BusinessError } from '@kit.BasicServicesKit'; import { TestA } from './Test'; @Concurrent async function test1(arg: TestA) { console.info("TestA name is: " + arg.name); } @Entry @Component struct Index { @State message: string = 'Hello World'; build() { RelativeContainer() { Text(this.message) .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: '__container__', align: VerticalAlign.Center }, middle: { anchor: '__container__', align: HorizontalAlign.Center } }) .onClick(() => { // 1. Create a test instance objA. let objA = new TestA("TestA"); // 2. Create a task and transfer objA to the task. objA is not a Sendable object and is transferred to the child thread through serialization. let task = new taskpool.Task(test1, objA); // 3. Execute the task. taskpool.execute(task).then(() => { console.info("taskpool: execute task success!"); }).catch((e:BusinessError) => { console.error(`taskpool: execute task: Code: ${e.code}, message: ${e.message}`); }) }) } .height('100%') .width('100%') } }
application-dev\arkts-utils\resident-task-guide.md
// Index.ets import { worker } from '@kit.ArkTS';
application-dev\arkts-utils\resident-task-guide.md
// Index.ets const workerInstance: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
application-dev\arkts-utils\resident-task-guide.md
// Index.ets @Entry @Component struct Index { build() { Column() { Text("Listener task") .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { workerInstance.postMessage({type: 'start'}) workerInstance.onmessage = (event) => { console.info('The UI main thread receives a message:', event.data); } // Stop the Worker thread after 10 seconds. setTimeout(() => { workerInstance.postMessage({ type: 'stop' }); }, 10000); }) } .height('100%') .width('100%') } }
application-dev\arkts-utils\resident-task-guide.md
// Worker.ets import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS'; const workerPort: ThreadWorkerGlobalScope = worker.workerPort; let isRunning = false; workerPort.onmessage = (e: MessageEvents) => { const type = e.data.type as string; if (type === 'start') { if (!isRunning) { isRunning = true; // Start a resident task. performTask(); } } else if (type === 'stop') { isRunning = false; workerPort.close(); // Close the Worker thread. } } // Simulate a resident task. function performTask() { if (isRunning) { // Simulate a long-running task. workerPort.postMessage('Worker is performing a task'); // Execute the task again after 1 second. setTimeout(performTask, 1000); } workerPort.postMessage('Worker is stop performing a task'); }
application-dev\arkts-utils\sendable-constraints.md
@Sendable class A { constructor() { } } @Sendable class B extends A { constructor() { super() } }
application-dev\arkts-utils\sendable-constraints.md
class A { constructor() { } } @Sendable class B extends A { // A is not a Sendable class. B cannot inherit it. A compilation error is reported. constructor() { super() } }
application-dev\arkts-utils\sendable-constraints.md
class A { constructor() { } } class B extends A { constructor() { super() } }
application-dev\arkts-utils\sendable-constraints.md
@Sendable class A { constructor() { } } class B extends A { // A is a Sendable class. B cannot inherit it. A compilation error is reported. constructor() { super() } }
application-dev\arkts-utils\sendable-constraints.md
interface I {}; class B implements I {};
application-dev\arkts-utils\sendable-constraints.md
import { lang } from '@kit.ArkTS'; type ISendable = lang.ISendable; interface I extends ISendable {}; class B implements I {}; // I is a Sendable interface. B cannot implement it. A compilation error is reported.
application-dev\arkts-utils\sendable-constraints.md
@Sendable class A { constructor() { } a: number = 0; }
application-dev\arkts-utils\sendable-constraints.md
@Sendable class A { constructor() { } b: Array<number> = [1, 2, 3] // A compilation error is reported. Use collections.Array instead. }
application-dev\arkts-utils\sendable-constraints.md
@Sendable class A { constructor() { } a: number = 0; }
application-dev\arkts-utils\sendable-constraints.md
@Sendable class A { constructor() { } a!: number; // A compilation error is reported. The exclamation mark (!) is not supported. }
application-dev\arkts-utils\sendable-constraints.md
@Sendable class A { num1: number = 1; num2: number = 2; add(): number { return this.num1 + this.num2; } }
application-dev\arkts-utils\sendable-constraints.md
enum B { b1 = "bbb" } @Sendable class A { ["aaa"]: number = 1; // A compilation error is reported. ["aaa"] is not supported. [B.b1]: number = 2; // A compilation error is reported. [B.b1] is not supported. }
application-dev\arkts-utils\sendable-constraints.md
import { collections } from '@kit.ArkTS'; try { let arr1: collections.Array<number> = new collections.Array<number>(); let num: number = 1; arr1.push(num); } catch (e) { console.error(`taskpool execute: Code: ${e.code}, message: ${e.message}`); }
application-dev\arkts-utils\sendable-constraints.md
import { collections } from '@kit.ArkTS'; try { let arr1: collections.Array<Array<number>> = new collections.Array<Array<number>>(); // A compilation error is reported. The template type must be Sendable. let arr2: Array<number> = new Array<number>(); arr2.push(1); arr1.push(arr2); } catch (e) { console.error(`taskpool execute: Code: ${e.code}, message: ${e.message}`); }
application-dev\arkts-utils\sendable-constraints.md
import { lang } from '@kit.ArkTS'; type ISendable = lang.ISendable; interface I extends ISendable {} @Sendable class B implements I { static o: number = 1; static bar(): B { return new B(); } } @Sendable class C { v: I = new B(); u: number = B.o; foo() { return B.bar(); } }
application-dev\arkts-utils\sendable-constraints.md
import { lang } from '@kit.ArkTS'; type ISendable = lang.ISendable; interface I extends ISendable {} @Sendable class B implements I {} function bar(): B { return new B(); } let b = new B(); { @Sendable class A implements I {} @Sendable class C { u: I = bar(); // bar is not a Sendable class object. A compile-time error is reported. v: I = new A(); // A is not defined at the top level. A compile-time error is reported. foo() { return b; // b is not a Sendable class object but an instance of the Sendable class. A compile-time error is reported. } } }
application-dev\arkts-utils\sendable-constraints.md
@Sendable type SendableFuncType = () => void; @Sendable class C {} @Sendable function SendableFunc() { console.info("Sendable func"); }
application-dev\arkts-utils\sendable-constraints.md
@Sendable type A = number; // A compile-time error is reported. @Sendable type D = C; // A compile-time error is reported.
application-dev\arkts-utils\sendable-constraints.md
@Sendable class A { num: number = 1; }
application-dev\arkts-utils\sendable-constraints.md
@Sendable @Observed // A compilation error is reported. class C { num: number = 1; }
application-dev\arkts-utils\sendable-constraints.md
import { collections } from '@kit.ArkTS'; let arr1: collections.Array<number> = new collections.Array<number>(1, 2, 3); // The type is Sendable.
application-dev\arkts-utils\sendable-constraints.md
import { collections } from '@kit.ArkTS'; let arr2: collections.Array<number> = [1, 2, 3]; // The type is not Sendable. A compile-time error is reported. let arr3: number[] = [1, 2, 3]; // The type is not Sendable. No error is reported. let arr4: number[] = new collections.Array<number>(1, 2, 3); // A compile-time error is reported.
application-dev\arkts-utils\sendable-constraints.md
class A { state: number = 0; } @Sendable class SendableA { state: number = 0; } let a1: A = new SendableA() as A;
application-dev\arkts-utils\sendable-constraints.md
class A { state: number = 0; } @Sendable class SendableA { state: number = 0; } let a2: SendableA = new A() as SendableA; // A compilation error is reported.
application-dev\arkts-utils\sendable-constraints.md
@Sendable type SendableFuncType = () => void; @Sendable function SendableFunc() { console.info("Sendable func"); } @Sendable class SendableClass { constructor(f: SendableFuncType) { this.func = f; } func: SendableFuncType; } let sendableClass = new SendableClass(SendableFunc);
application-dev\arkts-utils\sendable-constraints.md
@Sendable type SendableFuncType = () => void; let func: SendableFuncType = () => {}; // A compile-time error is reported. @Sendable class SendableClass { func: SendableFuncType = () => {}; // A compile-time error is reported. }
application-dev\arkts-utils\sendable-freeze.md
// helper.ts export function freezeObj(obj: any) { Object.freeze(obj); }
application-dev\arkts-utils\sendable-freeze.md
// Index.ets import { freezeObj } from './helper'; import { worker } from '@kit.ArkTS'; @Sendable export class GlobalConfig { // Configuration properties and methods init() { // Initialization logic freezeObj(this) // Freeze the object after the initialization is complete. } } @Entry @Component struct Index { build() { Column() { Text("Sendable freezeObj Test") .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { let gConfig = new GlobalConfig(); gConfig.init(); const workerInstance = new worker.ThreadWorker('entry/ets/workers/Worker.ets', { name: "Worker1" }); workerInstance.postMessage(gConfig); }) } .height('100%') .width('100%') } }
application-dev\arkts-utils\sendable-freeze.md
// Worker.ets import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS'; import { GlobalConfig } from '../pages/Index'; const workerPort: ThreadWorkerGlobalScope = worker.workerPort; workerPort.onmessage = (e: MessageEvents) => { let gConfig: GlobalConfig = e.data; // Use the gConfig object. }
application-dev\arkts-utils\sendable-guide.md
// Index.ets import { taskpool } from '@kit.ArkTS'; import { testTypeA, testTypeB, Test } from './sendable'; import { BusinessError, emitter } from '@kit.BasicServicesKit'; // Simulate data processing in a concurrent function. @Concurrent async function taskFunc(obj: Test) { console.info("test task res1 is: " + obj.data1.name + " res2 is: " + obj.data2.name); } async function test() { // Use TaskPool to pass data. let a: testTypeA = new testTypeA("testTypeA"); let b: testTypeB = new testTypeB("testTypeB"); let obj: Test = new Test(a, b); let task: taskpool.Task = new taskpool.Task(taskFunc, obj); await taskpool.execute(task); } @Concurrent function SensorListener() { // Listening logic // ... } @Entry @Component struct Index { build() { Column() { Text("Listener task") .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { let sensorTask = new taskpool.LongTask(SensorListener); emitter.on({ eventId: 0 }, (data) => { // Do something here console.info(`Receive ACCELEROMETER data: {${data.data?.x}, ${data.data?.y}, ${data.data?.z}`); }); taskpool.execute(sensorTask).then(() => { console.info("Add listener of ACCELEROMETER success"); }).catch((e: BusinessError) => { // Process error }) }) Text("Data processing task") .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { test(); }) } .height('100%') .width('100%') } }
application-dev\arkts-utils\sendable-guide.md
// sendable.ets // Assemble large data in a Sendable class. @Sendable export class testTypeA { name: string = "A"; constructor(name: string) { this.name = name; } } @Sendable export class testTypeB { name: string = "B"; constructor(name: string) { this.name = name; } } @Sendable export class Test { data1: testTypeA; data2: testTypeB; constructor(arg1: testTypeA, arg2: testTypeB) { this.data1 = arg1; this.data2 = arg2; } }
application-dev\arkts-utils\sendable-guide.md
// Index.ets import { taskpool, ArkTSUtils } from '@kit.ArkTS'; import { SendableTestClass, ISendable } from './sendable'; // Simulate data processing in a concurrent function. @Concurrent async function taskFunc(sendableObj: SendableTestClass) { console.info("SendableTestClass: name is: " + sendableObj.printName() + ", age is: " + sendableObj.printAge() + ", sex is: " + sendableObj.printSex()); sendableObj.setAge(28); console.info("SendableTestClass: age is: " + sendableObj.printAge()); // Parse the sendableObj.arr data to generate a JSON string. let str = ArkTSUtils.ASON.stringify(sendableObj.arr); console.info("SendableTestClass: str is: " + str); // Parse the data and generate ISendable data. let jsonStr = '{"name": "Alexa", "age": 23, "sex": "female"}'; let obj = ArkTSUtils.ASON.parse(jsonStr) as ISendable; console.info("SendableTestClass: type is: " + typeof obj); console.info("SendableTestClass: name is: " + (obj as object)?.["name"]); // Output: 'Alexa' console.info("SendableTestClass: age is: " + (obj as object)?.["age"]); // Output: 23 console.info("SendableTestClass: sex is: " + (obj as object)?.["sex"]); // Output: 'female' } async function test() { // Use TaskPool to pass data. let obj: SendableTestClass = new SendableTestClass(); let task: taskpool.Task = new taskpool.Task(taskFunc, obj); await taskpool.execute(task); } @Entry @Component struct Index { @State message: string = 'Hello World'; build() { RelativeContainer() { Text(this.message) .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: '__container__', align: VerticalAlign.Center }, middle: { anchor: '__container__', align: HorizontalAlign.Center } }) .onClick(() => { test(); }) } .height('100%') .width('100%') } }
application-dev\arkts-utils\sendable-guide.md
// sendable.ets // Define a Test class to simulate the operation of passing a class instance carrying methods. import { lang, collections } from '@kit.ArkTS' export type ISendable = lang.ISendable; @Sendable export class SendableTestClass { name: string = 'John'; age: number = 20; sex: string = "man"; arr: collections.Array<number> = new collections.Array<number>(1, 2, 3); constructor() { } setAge(age: number) : void { this.age = age; } printName(): string { return this.name; } printAge(): number { return this.age; } printSex(): string { return this.sex; } }
application-dev\arkts-utils\sendablelrucache-recent-list.md
// LruCache.ets import { ArkTSUtils } from '@kit.ArkTS'; // Use the 'use shared' marker to mark a module shareable. "use shared" // The SendableClass instance can be shared across different threads. @Sendable class SendableClass { // Lock the SendableLruCache instances to prevent data inconsistency caused by concurrent operations from multiple threads. lock_: ArkTSUtils.locks.AsyncLock = new ArkTSUtils.locks.AsyncLock(); books_: ArkTSUtils.SendableLruCache<string, string> = new ArkTSUtils.SendableLruCache<string, string>(4); constructor() { this.books_.put("fourth", "Book4"); this.books_.put("third", "Book3"); this.books_.put("second", "Book2"); this.books_.put("first", "Book1"); } // Wrap the put, get, and keys methods and perform the lock operation. public async put(key: string, value: string) { await this.lock_.lockAsync(() => { this.books_.put(key, value); }) } public async get(key: string): Promise<string | undefined> { return this.lock_.lockAsync(() => { return this.books_.get(key); }); } public async keys(): Promise<string[]> { return this.lock_.lockAsync(() => { return this.books_.keys(); }); } } export let lruCache = new SendableClass();
application-dev\arkts-utils\sendablelrucache-recent-list.md
// Book1.ets @Entry @Component struct Index1 { @State message: string = 'Hello World!'; build() { RelativeContainer() { Text("Content of book 1") .id('first book') .fontSize(20) .padding(10) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: 'container', align: VerticalAlign.Center }, middle: { anchor: 'container', align: HorizontalAlign.Center } }) Button('Back') .fontSize(20) .padding(10) .fontWeight(FontWeight.Bold) .onClick(() => { this.getUIContext().getRouter().pushUrl({ url: 'pages/Index' }); }) } .height('100%') .width('100%') } }
application-dev\arkts-utils\sendablelrucache-recent-list.md
// Book2.ets @Entry @Component struct Index2 { @State message: string = 'Hello World!'; build() { RelativeContainer() { Text("Content of book 2") .id('second book') .fontSize(20) .padding(10) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: 'container', align: VerticalAlign.Center }, middle: { anchor: 'container', align: HorizontalAlign.Center } }) Button('Back') .fontSize(20) .padding(10) .fontWeight(FontWeight.Bold) .onClick(() => { this.getUIContext().getRouter().pushUrl({ url: 'pages/Index' }); }) } .height('100%') .width('100%') } }
application-dev\arkts-utils\sendablelrucache-recent-list.md
// Book3.ets @Entry @Component struct Index3 { @State message: string = 'Hello World!'; build() { RelativeContainer() { Text("Content of book 3") .id('third book') .fontSize(20) .padding(10) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: 'container', align: VerticalAlign.Center }, middle: { anchor: 'container', align: HorizontalAlign.Center } }) Button('Back') .fontSize(20) .padding(10) .fontWeight(FontWeight.Bold) .onClick(() => { this.getUIContext().getRouter().pushUrl({ url: 'pages/Index' }); }) } .height('100%') .width('100%') } }
application-dev\arkts-utils\sendablelrucache-recent-list.md
// Book4.ets @Entry @Component struct Index4 { @State message: string = 'Hello World!'; build() { RelativeContainer() { Text("Content of book 4") .id('fourth book') .fontSize(20) .padding(10) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: 'container', align: VerticalAlign.Center }, middle: { anchor: 'container', align: HorizontalAlign.Center } }) Button('Back') .fontSize(20) .padding(10) .fontWeight(FontWeight.Bold) .onClick(() => { this.getUIContext().getRouter().pushUrl({ url: 'pages/Index' }); }) } .height('100%') .width('100%') } }
application-dev\arkts-utils\sendablelrucache-recent-list.md
// Index.ets import { taskpool } from '@kit.ArkTS'; import { lruCache } from './LruCache' @Concurrent async function updateBooks(key: string, value: string) { // Update the latest access list in the child thread. await lruCache.put(key, value); } @Entry @Component struct Index { @State message: string = 'Bookshelf' @State books: string[] = []; async aboutToAppear () { // The application automatically obtains the list of recently accessed books. this.books = await lruCache.keys(); } build() { Column({ space: 1 }) { Text(this.message) .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: 'container', align: VerticalAlign.Center }, middle: { anchor: 'container', align: HorizontalAlign.Center } }) Button(this.books[3]) .fontSize(20) .padding(10) .fontWeight(FontWeight.Bold) .onClick(async () => { // Obtain the bound book information. let value = await lruCache.get(this.books[3]); // Update the recently accessed list. taskpool.execute(updateBooks, this.books[3], value); this.getUIContext().getRouter().pushUrl({ url: 'pages/' + value }); }) Button(this.books[2]) .fontSize(20) .padding(10) .fontWeight(FontWeight.Bold) .onClick(async () => { // Obtain the bound book information. let value = await lruCache.get(this.books[2]); // Update the recently accessed list. taskpool.execute(updateBooks, this.books[2], value); this.getUIContext().getRouter().pushUrl({ url: 'pages/' + value }); }) Button(this.books[1]) .fontSize(20) .padding(10) .fontWeight(FontWeight.Bold) .onClick(async () => { // Obtain the bound book information. let value = await lruCache.get(this.books[1]); // Update the recently accessed list. taskpool.execute(updateBooks, this.books[1], value); this.getUIContext().getRouter().pushUrl({ url: 'pages/' + value }); }) Button(this.books[0]) .fontSize(20) .padding(10) .fontWeight(FontWeight.Bold) .onClick(async () => { // Obtain the bound book information. let value = await lruCache.get(this.books[0]); // Update the recently accessed list. taskpool.execute(updateBooks, this.books[0], value); this.getUIContext().getRouter().pushUrl({ url: 'pages/' + value }); }) } .height('100%') .width('100%') } }
application-dev\arkts-utils\shared-arraybuffer-object.md
import { taskpool } from '@kit.ArkTS'; @Concurrent function transferAtomics(arg1: Int32Array) { console.info("wait begin::"); // Use Atomics to perform operations. let res = Atomics.wait(arg1, 0, 0, 3000); return res; } // Define an object that can be shared. let sab: SharedArrayBuffer = new SharedArrayBuffer(20); let int32 = new Int32Array(sab); let task: taskpool.Task = new taskpool.Task(transferAtomics, int32); taskpool.execute(task).then((res) => { console.info("this res is: " + res); }); setTimeout(() => { Atomics.notify(int32, 0, 1); }, 1000);
application-dev\arkts-utils\sync-task-development.md
// Index.ets code import { taskpool} from '@kit.ArkTS'; // Step 1: Define a concurrent function to implement service logic. @Concurrent async function taskpoolFunc(num: number): Promise<number> { // Implement the corresponding functionality based on the service logic. let tmpNum: number = num + 100; return tmpNum; } async function mainFunc(): Promise<void> { // Step 2: Create and execute a task. let task1: taskpool.Task = new taskpool.Task(taskpoolFunc, 1); let res1: number = await taskpool.execute(task1) as number; let task2: taskpool.Task = new taskpool.Task(taskpoolFunc, res1); let res2: number = await taskpool.execute(task2) as number; // Step 3: Perform operations on the result returned by the task. console.info("taskpool: task res1 is: " + res1); console.info("taskpool: task res2 is: " + res2); } @Entry @Component struct Index { @State message: string = 'Hello World'; build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(async () => { mainFunc(); }) } .width('100%') .height('100%') } } }
application-dev\arkts-utils\sync-task-development.md
// Index.ets import { worker } from '@kit.ArkTS'; @Entry @Component struct Index { @State message: string = 'Hello World'; build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { let w: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); w.onmessage = (): void => { // Receive results from the Worker thread. } w.onAllErrors = (): void => { // Receive error messages from the Worker thread. } // Send a Set message to the Worker thread. w.postMessage({'type': 0, 'data': 'data'}) // Send a Get message to the Worker thread. w.postMessage({'type': 1}) // ... // Destroy the thread based on actual service requirements. w.terminate() }) } .width('100%') } .height('100%') } }
application-dev\arkts-utils\sync-task-development.md
// handle.ts code export default class Handle { syncGet() { return; } syncSet(num: number) { return; } }
application-dev\arkts-utils\sync-task-development.md
// MyWorker.ts code import { worker, ThreadWorkerGlobalScope, MessageEvents } from '@kit.ArkTS'; import Handle from './handle' // Import the handle. let workerPort : ThreadWorkerGlobalScope = worker.workerPort; // Handle that cannot be transferred. All operations depend on this handle. let handler: Handle = new Handle() // onmessage() logic of the Worker thread. workerPort.onmessage = (e : MessageEvents): void => { switch (e.data.type as number) { case 0: handler.syncSet(e.data.data); workerPort.postMessage('success set'); break; case 1: handler.syncGet(); workerPort.postMessage('success get'); break; } }
application-dev\arkts-utils\taskpool-async-task-guide.md
// Index.ets import { taskpool } from '@kit.ArkTS'; import { BusinessError, emitter } from '@kit.BasicServicesKit';
application-dev\arkts-utils\taskpool-async-task-guide.md
// Index.ets @Concurrent function collectFrame() { // Collect and process data. // Simulate the processing task, which is time consuming. let t = new Date().getTime() while (new Date().getTime() - t < 30000) { continue; } }
application-dev\arkts-utils\taskpool-async-task-guide.md
// Index.ets @Entry @Component struct Index { sensorTask?: taskpool.LongTask build() { Column() { Text("HELLO WORLD") .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { // Create an asynchronous queue with a concurrency level of 5 and a queue capacity of 5. let asyncRunner:taskpool.AsyncRunner = new taskpool.AsyncRunner("async", 5, 5); // Trigger the collection task every second. setTimeout(() => { let task:taskpool.Task = new taskpool.Task(collectFrame); asyncRunner.execute(task); }, 1000); }) } .height('100%') .width('100%') } }
application-dev\arkts-utils\taskpool-communicates-with-mainthread.md
// TaskSendDataUsage.ets function notice(data: number): void { console.info("Child thread task completed. Total images loaded:", data) }
application-dev\arkts-utils\taskpool-communicates-with-mainthread.md
// IconItemSource.ets export class IconItemSource { image: string | Resource = ''; text: string | Resource = ''; constructor(image: string | Resource = '', text: string | Resource = '') { this.image = image; this.text = text; } }
application-dev\arkts-utils\taskpool-communicates-with-mainthread.md
// TaskSendDataUsage.ets import { taskpool } from '@kit.ArkTS'; import { IconItemSource } from './IconItemSource'; // Use sendData to notify the host thread of information in real time. @Concurrent export function loadPictureSendData(count: number): IconItemSource[] { let iconItemSourceList: IconItemSource[] = []; // Add six IconItem data records. for (let index = 0; index < count; index++) { const numStart: number = index * 6; // Use six images in the loop. iconItemSourceList.push(new IconItemSource('$media:startIcon', `item${numStart + 1}`)); iconItemSourceList.push(new IconItemSource('$media:background', `item${numStart + 2}`)); iconItemSourceList.push(new IconItemSource('$media:foreground', `item${numStart + 3}`)); iconItemSourceList.push(new IconItemSource('$media:startIcon', `item${numStart + 4}`)); iconItemSourceList.push(new IconItemSource('$media:background', `item${numStart + 5}`)); iconItemSourceList.push(new IconItemSource('$media:foreground', `item${numStart + 6}`)); taskpool.Task.sendData(iconItemSourceList.length); } return iconItemSourceList; }
application-dev\arkts-utils\taskpool-communicates-with-mainthread.md
// TaskSendDataUsage.ets @Entry @Component struct Index { @State message: string = 'Hello World'; build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { let iconItemSourceList: IconItemSource[]; let loadPictureTask: taskpool.Task = new taskpool.Task(loadPictureSendData, 30); // Use notice to receive messages from the task. loadPictureTask.onReceiveData(notice); taskpool.execute(loadPictureTask).then((res: object) => { iconItemSourceList = res as IconItemSource[]; }) }) } .width('100%') } .height('100%') } }
application-dev\arkts-utils\taskpool-introduction.md
import { taskpool } from '@kit.ArkTS'; import { BusinessError } from '@kit.BasicServicesKit'; @Concurrent function printArrayBuffer(buffer: ArrayBuffer) { return buffer; } function testArrayBuffer() { const buffer = new ArrayBuffer(1); const group = new taskpool.TaskGroup(); const task = new taskpool.Task(printArrayBuffer, buffer); group.addTask(task); task.setCloneList([buffer]); for (let i = 0; i < 5; i++) { taskpool.execute(group).then(() => { console.info('execute group success'); }).catch((e: BusinessError) => { console.error(`execute group error: ${e.message}`); }) } }
application-dev\arkts-utils\taskpool-introduction.md
> function bar() { > } > > @Concurrent > function foo() { > bar(); // This violates the closure principle. An error is reported. > } >
application-dev\arkts-utils\taskpool-introduction.md
import { taskpool } from '@kit.ArkTS'; @Concurrent function add(num1: number, num2: number): number { return num1 + num2; } async function concurrentFunc(): Promise<void> { try { const task: taskpool.Task = new taskpool.Task(add, 1, 2); console.info(`taskpool res is: ${await taskpool.execute(task)}`); // Output: taskpool res is: 3 } catch (e) { console.error(`taskpool execute error is: ${e}}`); } } @Entry @Component struct Index { @State message: string = 'Hello World'; build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { concurrentFunc(); }) } .width('100%') } .height('100%') } }
application-dev\arkts-utils\taskpool-introduction.md
import { taskpool } from '@kit.ArkTS'; @Concurrent function testPromise(args1: number, args2: number): Promise<number> { return new Promise<number>((resolve, reject) => { resolve(args1 + args2); }); } @Concurrent async function testPromise1(args1: number, args2: number): Promise<number> { return new Promise<number>((resolve, reject) => { resolve(args1 + args2); }); } @Concurrent async function testPromise2(args1: number, args2: number): Promise<number> { return await new Promise<number>((resolve, reject) => { resolve(args1 + args2); }); } @Concurrent function testPromise3() { return Promise.resolve(1); } @Concurrent async function testPromise4(): Promise<number> { return 1; } @Concurrent async function testPromise5(): Promise<string> { return await new Promise((resolve) => { setTimeout(() => { resolve('Promise setTimeout after resolve'); }, 1000) }); } async function testConcurrentFunc() { const task1: taskpool.Task = new taskpool.Task(testPromise, 1, 2); const task2: taskpool.Task = new taskpool.Task(testPromise1, 1, 2); const task3: taskpool.Task = new taskpool.Task(testPromise2, 1, 2); const task4: taskpool.Task = new taskpool.Task(testPromise3); const task5: taskpool.Task = new taskpool.Task(testPromise4); const task6: taskpool.Task = new taskpool.Task(testPromise5); taskpool.execute(task1).then((d: object) => { console.info(`task1 res is: ${d}`); // Output: task1 res is: 3 }).catch((e: object) => { console.error(`task1 catch e: ${e}`); }) taskpool.execute(task2).then((d: object) => { console.info(`task2 res is: ${d}`); }).catch((e: object) => { console.error(`task2 catch e: ${e}`); // Output: task2 catch e: Error: Can't return Promise in pending state }) taskpool.execute(task3).then((d: object) => { console.info(`task3 res is: ${d}`); // Output: task3 res is: 3 }).catch((e: object) => { console.error(`task3 catch e: ${e}`); }) taskpool.execute(task4).then((d: object) => { console.info(`task4 res is: ${d}`); // Output: task4 res is: 1 }).catch((e: object) => { console.error(`task4 catch e: ${e}`); }) taskpool.execute(task5).then((d: object) => { console.info(`task5 res is: ${d}`); // Output: task5 res is: 1 }).catch((e: object) => { console.error(`task5 catch e: ${e}`); }) taskpool.execute(task6).then((d: object) => { console.info(`task6 res is: ${d}`); // Output: task6 res is: Promise setTimeout after resolve }).catch((e: object) => { console.error(`task6 catch e: ${e}`); }) } @Entry @Component struct Index { @State message: string = 'Hello World'; build() { Row() { Column() { Button(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { testConcurrentFunc(); }) } .width('100%') } .height('100%') } }
application-dev\arkts-utils\taskpool-introduction.md
// Index.ets import { taskpool } from '@kit.ArkTS'; import { BusinessError } from '@kit.BasicServicesKit'; import { testAdd, MyTestA, MyTestB } from './Test'; function add(arg: number) { return ++arg; } class TestA { constructor(name: string) { this.name = name; } name: string = 'ClassA'; } class TestB { static nameStr: string = 'ClassB'; } @Concurrent function TestFunc() { // Case 1: Directly call a class or function defined in the same file within a concurrent function. // Directly call the add() function defined in the same file. The following error message is displayed: "Only imported variables and local variables can be used in @Concurrent decorated functions. <ArkTSCheck>" // add(1); // Directly use the TestA constructor defined in the same file. The following error message is displayed: "Only imported variables and local variables can be used in @Concurrent decorated functions. <ArkTSCheck>" // const a = new TestA('aaa'); // Directly access the nameStr member of TestB defined in the same file. The following error message is displayed: "Only imported variables and local variables can be used in @Concurrent decorated functions. <ArkTSCheck>" // console.info(`TestB name is: ${TestB.nameStr}`); // Case 2: In the concurrent function, call classes or functions defined in the Test.ets file and imported into the current file. // Output: res1 is: 2 console.info(`res1 is: ${testAdd(1)}`); const tmpStr = new MyTestA('TEST A'); // Output: res2 is: TEST A console.info(`res2 is: ${tmpStr.name}`); // Output: res3 is: MyTestB console.info(`res3 is: ${MyTestB.nameStr}`); } @Entry @Component struct Index { @State message: string = 'Hello World'; build() { RelativeContainer() { Text(this.message) .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: '__container__', align: VerticalAlign.Center }, middle: { anchor: '__container__', align: HorizontalAlign.Center } }) .onClick(() => { const task = new taskpool.Task(TestFunc); taskpool.execute(task).then(() => { console.info('taskpool: execute task success!'); }).catch((e: BusinessError) => { console.error(`taskpool: execute: Code: ${e.code}, message: ${e.message}`); }) }) } .height('100%') .width('100%') } }
application-dev\arkts-utils\taskpool-introduction.md
// Test.ets export function testAdd(arg: number) { return ++arg; } @Sendable export class MyTestA { constructor(name: string) { this.name = name; } name: string = 'MyTestA'; } export class MyTestB { static nameStr:string = 'MyTestB'; }
application-dev\arkts-utils\taskpool-introduction.md
import { taskpool } from '@kit.ArkTS'; @Concurrent async function testPromiseError() { await new Promise<number>((resolve, reject) => { resolve(1); }).then(() => { throw new Error('testPromise Error'); }) } @Concurrent async function testPromiseError1() { await new Promise<string>((resolve, reject) => { reject('testPromiseError1 Error msg'); }) } @Concurrent function testPromiseError2() { return new Promise<string>((resolve, reject) => { reject('testPromiseError2 Error msg'); }) } async function testConcurrentFunc() { const task1: taskpool.Task = new taskpool.Task(testPromiseError); const task2: taskpool.Task = new taskpool.Task(testPromiseError1); const task3: taskpool.Task = new taskpool.Task(testPromiseError2); taskpool.execute(task1).then((d: object) => { console.info(`task1 res is: ${d}`); }).catch((e: object) => { console.error(`task1 catch e: ${e}`); // task1 catch e: Error: testPromise Error }) taskpool.execute(task2).then((d: object) => { console.info(`task2 res is: ${d}`); }).catch((e: object) => { console.error(`task2 catch e: ${e}`); // task2 catch e: testPromiseError1 Error msg }) taskpool.execute(task3).then((d: object) => { console.info(`task3 res is: ${d}`); }).catch((e: object) => { console.error(`task3 catch e: ${e}`); // task3 catch e: testPromiseError2 Error msg }) } @Entry @Component struct Index { @State message: string = 'Hello World'; build() { Row() { Column() { Button(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { testConcurrentFunc(); }) } .width('100%') } .height('100%') } }
application-dev\arkts-utils\taskpool-waterflow.md
// Mock.ets import { taskpool } from '@kit.ArkTS'; import { fillImg } from './Index'; @Concurrent function query() { console.info("TaskPoolTest-this is query"); let result = new Array<string>(33); for (let i = 0; i < 33; i++) { result[i] = 'Image' + i; } taskpool.Task.sendData(result); } export function getImgFromDB() { // Simulate the operation of querying the database and returning data. let task = new taskpool.Task(query); task.onReceiveData(fillImg); taskpool.execute(task); }
application-dev\arkts-utils\taskpool-waterflow.md
// WaterFlowDataSource.ets // An object that implements the IDataSource interface, which is used by the WaterFlow component to load data. export class WaterFlowDataSource implements IDataSource { private dataArray: number[] = []; private listeners: DataChangeListener[] = []; constructor() { for (let i = 0; i < 100; i++) { this.dataArray.push(i); } } // Obtain the data corresponding to the specified index. public getData(index: number): number { return this.dataArray[index]; } // Notify the controller that data has been reloaded. notifyDataReload(): void { this.listeners.forEach(listener => { listener.onDataReloaded(); }) } // Notify the controller that data has been added. notifyDataAdd(index: number): void { this.listeners.forEach(listener => { listener.onDataAdd(index); }) } // Notify the controller that data has changed. notifyDataChange(index: number): void { this.listeners.forEach(listener => { listener.onDataChange(index); }) } // Notify the controller that data has been deleted. notifyDataDelete(index: number): void { this.listeners.forEach(listener => { listener.onDataDelete(index); }) } // Notify the controller that the data position has changed. notifyDataMove(from: number, to: number): void { this.listeners.forEach(listener => { listener.onDataMove(from, to); }) } //Notify the controller that data has been deleted in batch. notifyDatasetChange(operations: DataOperation[]): void { this.listeners.forEach(listener => { listener.onDatasetChange(operations); }) } // Obtain the total number of data records. public totalCount(): number { return this.dataArray.length; } // Register a controller for data changes. registerDataChangeListener(listener: DataChangeListener): void { if (this.listeners.indexOf(listener) < 0) { this.listeners.push(listener); } } // Unregister the controller for data changes. unregisterDataChangeListener(listener: DataChangeListener): void { const pos = this.listeners.indexOf(listener); if (pos >= 0) { this.listeners.splice(pos, 1); } } // Add data. public add1stItem(): void { this.dataArray.splice(0, 0, this.dataArray.length); this.notifyDataAdd(0); } // Add an element to the end of the data. public addLastItem(): void { this.dataArray.splice(this.dataArray.length, 0, this.dataArray.length); this.notifyDataAdd(this.dataArray.length - 1); } // Add an element at the specified index. public addItem(index: number): void { this.dataArray.splice(index, 0, this.dataArray.length); this.notifyDataAdd(index); } // Delete the first element. public delete1stItem(): void { this.dataArray.splice(0, 1); this.notifyDataDelete(0); } // Delete the second element. public delete2ndItem(): void { this.dataArray.splice(1, 1); this.notifyDataDelete(1); } // Delete the last element. public deleteLastItem(): void { this.dataArray.splice(-1, 1); this.notifyDataDelete(this.dataArray.length); } // Delete an element at the specified index. public deleteItem(index: number): void { this.dataArray.splice(index, 1); this.notifyDataDelete(index); } // Reload the data. public reload(): void { this.dataArray.splice(1, 1); this.dataArray.splice(3, 2); this.notifyDataReload(); } }
application-dev\arkts-utils\taskpool-waterflow.md
// Index.ets import { WaterFlowDataSource } from './WaterFlowDataSource'; import { getImgFromDB } from './Mock'; // Simulate an image array. let img = new Array<string>(33); export function fillImg(imgArr : Array<string>) { img = imgArr; } @Entry @Component struct WaterFlowDemo { @State minSize: number = 80; @State maxSize: number = 180; @State fontSize: number = 24; @State colors: number[] = [0xFFC0CB, 0xDA70D6, 0x6B8E23, 0x6A5ACD, 0x00FFFF, 0x00FF7F]; scroller: Scroller = new Scroller(); dataSource: WaterFlowDataSource = new WaterFlowDataSource(); private itemWidthArray: number[] = []; private itemHeightArray: number[] = []; // Calculate the width and height of a flow item. getSize() { let ret = Math.floor(Math.random() * this.maxSize); return (ret > this.minSize ? ret : this.minSize); } // Set the width and height array of the flow item. setItemSizeArray() { for (let i = 0; i < 100; i++) { this.itemWidthArray.push(this.getSize()); this.itemHeightArray.push(this.getSize()); } } aboutToAppear() { this.setItemSizeArray(); } @Builder itemFoot() { Column() { Text(`Footer`) .fontSize(10) .backgroundColor(Color.Red) .width(50) .height(50) .align(Alignment.Center) .margin({ top: 2 }); } } build() { Column({ space: 2 }) { Text("ArkUI WaterFlow Demo") .onAppear(()=>{ getImgFromDB(); }) WaterFlow() { LazyForEach(this.dataSource, (item: number) => { FlowItem() { Column() { Text("N" + item) .fontSize(12) .height('16') .onClick(()=>{ }); // To simulate image loading, use the Text component. For actual JPG loading, use the Image component directly. Example: Image(this.img[item % 33]).objectFit(ImageFit.Contain).width('100%').layoutWeight(1) if (img[item % 33] == null) { Text('Loading image...') .width('100%') .layoutWeight(1); } Text(img[item % 33]) .width('100%') .layoutWeight(1); } } .onAppear(() => { // Pre-load more data when approaching the bottom. if (item + 20 == this.dataSource.totalCount()) { for (let i = 0; i < 100; i++) { this.dataSource.addLastItem(); } } }) .width('100%') .height(this.itemHeightArray[item % 100]) .backgroundColor(this.colors[item % 5]) }, (item: string) => item) } .columnsTemplate("1fr 1fr") .columnsGap(10) .rowsGap(5) .backgroundColor(0xFAEEE0) .width('100%') .height('100%') .onReachStart(() => { console.info('TaskPoolTest-waterFlow reach start'); }) .onScrollStart(() => { console.info('TaskPoolTest-waterFlow scroll start'); }) .onScrollStop(() => { console.info('TaskPoolTest-waterFlow scroll stop'); }) .onScrollFrameBegin((offset: number, state: ScrollState) => { console.info('TaskPoolTest-waterFlow scrollFrameBegin offset: ' + offset + ' state: ' + state.toString()); return { offsetRemain: offset }; }) } } }
application-dev\arkts-utils\transferabled-object.md
// Index.ets import { taskpool } from '@kit.ArkTS'; import { loadPixelMap } from './pixelMapTest'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct Index { @State message: string = 'Hello World'; @State pixelMap: PixelMap | undefined = undefined; private loadImageFromThread(): void { let context : Context = this.getUIContext().getHostContext() as Context; const resourceMgr = context.resourceManager; // startIcon.png is copied from the media directory to the rawfile folder. You need to replace it. Otherwise, the imageSource fails to be created and subsequent operations cannot be performed. resourceMgr.getRawFd('startIcon.png').then(rawFileDescriptor => { taskpool.execute(loadPixelMap, rawFileDescriptor).then(pixelMap => { if (pixelMap) { this.pixelMap = pixelMap as PixelMap; console.log('Succeeded in creating pixelMap.'); // The main thread releases the pixelMap. Because setTransferDetached has been called when the child thread returns the pixelMap, the pixelMap can be released immediately. this.pixelMap.release(); } else { console.error('Failed to create pixelMap.'); } }).catch((e: BusinessError) => { console.error('taskpool execute loadPixelMap failed. Code: ' + e.code + ', message: ' + e.message); }); }); } build() { RelativeContainer() { Text(this.message) .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: 'container', align: VerticalAlign.Center }, middle: { anchor: 'container', align: HorizontalAlign.Center } }) .onClick(() => { this.loadImageFromThread(); }) } .height('100%') .width('100%') } }
application-dev\arkts-utils\transferabled-object.md
// pixelMapTest.ets import { image } from '@kit.ImageKit'; @Concurrent export async function loadPixelMap(rawFileDescriptor: number): Promise<PixelMap> { // Create an imageSource. const imageSource = image.createImageSource(rawFileDescriptor); // Create a pixelMap. const pixelMap = imageSource.createPixelMapSync(); // Release the imageSource. imageSource.release(); // Detach the reference of the original thread after the cross-thread transfer of the pixelMap is complete. pixelMap.setTransferDetached(true); // Return the pixelMap to the main thread. return pixelMap; }
application-dev\arkts-utils\worker-and-taskpool.md
// Index.ets import { worker } from '@kit.ArkTS'; @Entry @Component struct Index { @State message: string = 'Hello World'; build() { RelativeContainer() { Text(this.message) .id('HelloWorld') .fontSize($r('app.float.page_text_font_size')) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: '__container__', align: VerticalAlign.Center }, middle: { anchor: '__container__', align: HorizontalAlign.Center } }) .onClick(() => { // 1. Create a Worker instance. const myWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets'); // 2. Handle results from the Worker instance. myWorker.onmessage = (e) => { console.log('Main thread receives the final result:', e.data.result); myWorker.terminate(); // Destroy the Worker instance. }; // 3. Send a startup instruction to the Worker instance. myWorker.postMessage({ type: 'start', data: 10 }); }) } .height('100%') .width('100%') } }
application-dev\arkts-utils\worker-and-taskpool.md
// Worker.ets import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS'; import { taskpool } from '@kit.ArkTS'; const workerPort: ThreadWorkerGlobalScope = worker.workerPort; workerPort.onmessage = async (e: MessageEvents) => { if (e.data.type === 'start') { // Simulate data processing by the Worker instance. const processedData = heavyComputation(e.data.data); // Call TaskPool to execute concurrent tasks. const task = new taskpool.Task(parallelTask, processedData); const result = await taskpool.execute(task); console.log('Worker thread returns result: ', result); // Return the final result to the main thread. workerPort.postMessage({ status: 'success', result: result }); } } function heavyComputation(base: number): number { let sum = 0; for (let i = 0; i < base * 10; i++) { sum += Math.sqrt(i); } return sum; } @Concurrent function parallelTask(base: number): number { let total = 0; for (let i = 0; i < base; i++) { total += i % 2 === 0 ? i : -i; } console.log('TaskPool thread calculation result: ', total); return total; }
application-dev\arkts-utils\worker-communicates-with-mainthread.md
// Worker.ets import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS'; const workerPort: ThreadWorkerGlobalScope = worker.workerPort; // The Worker receives messages from the host thread and processes them accordingly. workerPort.onmessage = (e: MessageEvents): void => { if (e.data === 'hello world') { workerPort.postMessage('success'); } }
application-dev\arkts-utils\worker-communicates-with-mainthread.md
// Index.ets import { worker } from '@kit.ArkTS'; import { BusinessError } from '@kit.BasicServicesKit'; function promiseCase() { let p: Promise<void> = new Promise<void>((resolve: Function, reject: Function) => { setTimeout(() => { resolve(1); }, 100) }).then(undefined, (error: BusinessError) => { }) return p; } async function postMessageTest() { let ss = new worker.ThreadWorker("entry/ets/workers/Worker.ets"); let res = undefined; let flag = false; let isTerminate = false; ss.onexit = () => { isTerminate = true; } // Receive messages sent by the Worker thread. ss.onmessage = (e) => { res = e.data; flag = true; console.info("worker:: res is " + res); } // Send a message to the Worker thread. ss.postMessage("hello world"); while (!flag) { await promiseCase(); } ss.terminate(); while (!isTerminate) { await promiseCase(); } } @Entry @Component struct Index { @State message: string = 'Hello World'; build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { postMessageTest(); }) } .width('100%') } .height('100%') } }
application-dev\arkts-utils\worker-introduction.md
// Import the module. import { worker } from '@kit.ArkTS'; // Use the following function in API version 9 and later versions: const worker1: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/worker.ets'); // Use the following function in API version 8 and earlier versions: const worker2: worker.Worker = new worker.Worker('entry/ets/workers/worker.ets');
application-dev\arkts-utils\worker-introduction.md
import { worker } from '@kit.ArkTS'; // URL of the Worker thread file: "entry/src/main/ets/workers/worker.ets" const workerStage1: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/worker.ets'); // URL of the Worker thread file: "testworkers/src/main/ets/ThreadFile/workers/worker.ets" const workerStage2: worker.ThreadWorker = new worker.ThreadWorker('testworkers/ets/ThreadFile/workers/worker.ets');
application-dev\arkts-utils\worker-introduction.md
import { worker } from '@kit.ArkTS'; // URL of the Worker thread file: "hsp/src/main/ets/workers/worker.ets" const workerStage3: worker.ThreadWorker = new worker.ThreadWorker('hsp/ets/workers/worker.ets');
application-dev\arkts-utils\worker-introduction.md
import { worker } from '@kit.ArkTS'; // @ path loading: // URL of the Worker thread file: "har/src/main/ets/workers/worker.ets" const workerStage4: worker.ThreadWorker = new worker.ThreadWorker('@har/ets/workers/worker.ets'); // Relative path loading: // URL of the Worker thread file: "har/src/main/ets/workers/worker.ets" // URL of the file where the Worker object is created: "har/src/main/ets/components/mainpage/MainPage.ets" const workerStage5: worker.ThreadWorker = new worker.ThreadWorker('../../workers/worker.ets');
application-dev\arkts-utils\worker-introduction.md
import { worker } from '@kit.ArkTS'; // The following three scenarios are involved. // Scenario 1: URL of the Worker thread file: "{moduleName}/src/main/ets/MainAbility/workers/worker.ets" const workerFA1: worker.ThreadWorker = new worker.ThreadWorker('workers/worker.ets', {name:'first worker in FA model'}); // Scenario 2: URL of the Worker thread file: "{moduleName}/src/main/ets/workers/worker.ets" const workerFA2: worker.ThreadWorker = new worker.ThreadWorker('../workers/worker.ets'); // Scenario 3: URL of the Worker thread file: "{moduleName}/src/main/ets/MainAbility/ThreadFile/workers/worker.ets" const workerFA3: worker.ThreadWorker = new worker.ThreadWorker('ThreadFile/workers/worker.ets');