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/*
24 * WorkerTask
25 *
26 * Work sub thread task
27 */
28export abstract class WorkerTask {
29  workerPort: ThreadWorkerGlobalScope
30
31  constructor(workerPort: ThreadWorkerGlobalScope) {
32    HiLog.i(TAG, `WorkerTask constructor`)
33    this.workerPort = workerPort;
34  }
35
36  /**
37   * Defines the event handler to be called when the worker thread receives a message sent by the host thread.
38   * The event handler is executed in the worker thread.
39   *
40   * @param e message data
41   */
42  public onmessage(message: MessageEvents) {
43    let data = <WorkerMessage> message.data
44    HiLog.i(TAG, `onmessage ${data.request}`)
45    try {
46      this.runInWorker(data.request, (v) => {
47        HiLog.i(TAG, 'runInWorker callback in')
48        data.param = v;
49        const str = JSON.stringify(data)
50        let buf = buffer.from(str).buffer;
51        this.workerPort.postMessage(buf, [buf]);
52      }, data.param);
53    } catch (err) {
54      HiLog.e(TAG, 'runInWorker err = ' + JSON.stringify(err));
55    }
56  }
57
58  public abstract runInWorker(request: string, callBack: (v?: any) => void, param?: any);
59}
60
61export default WorkerTask;