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 ServiceExtensionContext from "application/ServiceExtensionContext"; 17import Log from "../Log"; 18import createOrGet from "../SingleInstanceHelper"; 19import { EventParser, START_ABILITY_EVENT, Event, LocalEvent } from "./EventUtil"; 20import { Callback, createEventBus, EventBus } from "./EventBus"; 21 22export type unsubscribe = () => void; 23export type Events = string | string[]; 24 25const TAG = "EventManagerSc"; 26 27class EventManager { 28 mEventBus: EventBus<string>; 29 eventParser: EventParser; 30 mContext: ServiceExtensionContext | undefined; 31 32 constructor() { 33 this.mEventBus = createEventBus(); 34 this.eventParser = { 35 local: this.publishLocalEvent, 36 ability: this.startAbility, 37 commonEvent: this.publishCommonEvent, 38 remote: this.publishRemoteEvent, 39 }; 40 } 41 42 setContext(ctx: ServiceExtensionContext) { 43 this.mContext = ctx; 44 } 45 46 publish(event: Event): boolean { 47 return this.eventParser[event.target].call(this, event.data); 48 } 49 50 subscribe(eventType: Events, callback: Callback): unsubscribe { 51 return this.mEventBus.on(eventType, callback); 52 } 53 54 subscribeOnce(eventType: string, callback: Callback): unsubscribe { 55 return this.mEventBus.once(eventType, callback); 56 } 57 58 private publishLocalEvent(data: LocalEvent): boolean { 59 Log.showInfo(TAG, `publish localEvent type: ${data.eventName}`); 60 if (data.eventName) { 61 this.mEventBus.emit(data.eventName, data.args); 62 return true; 63 } 64 return false; 65 } 66 67 private startAbility(data: { [key: string]: any }): boolean { 68 Log.showInfo(TAG, `start Ability: ${data.abilityName}`); 69 if (data.bundleName && data.abilityName && this.mContext) { 70 this.mEventBus.emit(START_ABILITY_EVENT, { abilityName: data.abilityName }); 71 this.mContext.startAbility({ 72 bundleName: data.bundleName, 73 abilityName: data.abilityName, 74 parameters: data.args??undefined 75 }); 76 return true; 77 } 78 return false; 79 } 80 81 private publishRemoteEvent(data: { [key: string]: any }): boolean { 82 return false; 83 } 84 85 private publishCommonEvent(data: { [key: string]: any }): boolean { 86 return false; 87 } 88} 89 90let sEventManager = createOrGet(EventManager, TAG); 91 92export default sEventManager as EventManager;