• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/**
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import { WorkerMessage } from "./WorkerWrapper"
17import { ThreadWorkerGlobalScope, MessageEvents } from '@ohos.worker';
18import HiLog from '../../utils/HiLog';
19import buffer from "@ohos.buffer"
20
21const TAG = "WorkerTask"
22/*
23 * WorkerTask
24 *
25 * Work sub thread task
26 */
27export abstract class WorkerTask {
28    workerPort: ThreadWorkerGlobalScope
29
30    constructor(workerPort: ThreadWorkerGlobalScope) {
31        HiLog.i(TAG, `WorkerTask constructor`)
32        this.workerPort = workerPort;
33    }
34
35    /**
36     * Defines the event handler to be called when the worker thread receives a message sent by the host thread.
37     * The event handler is executed in the worker thread.
38     *
39     * @param e message data
40     */
41    public onmessage(message: MessageEvents) {
42        let data = <WorkerMessage> message.data
43        HiLog.i(TAG, `onmessage ${data.request}`)
44        try {
45            this.runInWorker(data.request, (v) => {
46                HiLog.i(TAG, "runInWorker callback in")
47                data.param = v;
48                const str = JSON.stringify(data)
49                let buf = buffer.from(str).buffer;
50                this.workerPort.postMessage(buf, [buf]);
51            }, data.param);
52        } catch (err) {
53            HiLog.e(TAG, 'runInWorker err = ' + JSON.stringify(err));
54        }
55    }
56
57    public abstract runInWorker(request: string, callBack: (v?: any) => void, param?: any);
58}
59
60export default WorkerTask;