Tuanjie provides TypeScript interface that communicate with the UI thread worker. That you can use to interact with your custom method in TypeScript plug-in code (.etslib).
If you want to call your custom method in Tuanjie UI thread worker, you can use this function : POST_MESSAGE_TO_HOST
import {POST_MESSAGE_TO_HOST} from './workers/HostProxy'
parameters in msg (ESObject):
modulePath:string : Dynamic Import module path,relative to the file :entry\src\main\ets\workers\MessageProcessor.ets;funcName:string : The function which you want to call, format is muduleName.functionName;args:Array<ESObject> : Function params, default value is empty [];callback:ESObject : Function callBack handler, default value is null;timeout:number : If you need a synchronous call (timeout = –1 ), or if you need an asynchronous call, please fill in the timeout (ms), default value is –1;// in TestClass.etslib
import {POST_MESSAGE_TO_HOST} from './workers/HostProxy'
export class ClassObjectTest {
Func1(arg1: string, arg2: boolean, arg3: number,arg4:ESObject, callback: (...args: Array<ESObject>) => ESObject) {
const param: Array<ESObject> = [
arg1,
arg2,
arg3,
arg4,
]
let msg:ESObject = {
modulePath: "../TestClassUI.ets",
funcName: "TestManager.Func1",
args: param,
callback: callback,
timeoutMs: 100000,
}
POST_MESSAGE_TO_HOST(msg);
}
public Func2(callback: (...args: Array<ESObject>) => ESObject) {
const param: Array<ESObject> = []
let msg:ESObject = {
modulePath: "../TestClassUI.ets",
funcName: "TestManager.Func2",
args: param,
callback: callback,
timeoutMs: -1,
}
POST_MESSAGE_TO_HOST(msg);
}
}
export function RegisterTestClass() {
const register :Record<string, Object> = {};
register["ClassObjectTest"] = ClassObjectTest;
return register;
}
//in TestClassUI.ets
import { BusinessError, emitter } from "@kit.BasicServicesKit";
import { hilog } from "@kit.PerformanceAnalysisKit";
export class TestManager {
//the return type is `Promise<Array<ESObject>>`
static async Func1(arg1: string, arg2: boolean, arg3: number,arg4:ESObject):Promise<Array<ESObject>>
{
return new Promise((resolve) => {
//if you need a context, you can use [globalThis.Abilitycontext] or [globalThis.UIContext]
CustomCall(arg1, arg2,arg3, arg4, globalThis.Abilitycontext).then((resultData:ESObject) => {
let result: Array<string> = ["result", resultData];
resolve(result);
}).catch((error: BusinessError) => {
let errorMsg :string = JSON.stringify(error);
let result:Array<ESObject> = [errorMsg];
resolve(result);
});
});
}
public async CustomCall(arg1: string, arg2: boolean, arg3: number,arg4:ESObject, context:common.Context):Promise<ESObject> {
// Write your code here ...
}
//the return type is `Array<string>`
static Func2(): Array<string> {
hilog.info(0x0001, "test", `call in UI thread`);
let resultData = "{\"code\":\"1\"}";
let result: Array<string> = ["result", resultData];
return result;
}
}