1/* 2 * Copyright (c) 2023 Hunan OpenValley Digital Industry Development 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 */ 15import TimerUtil, { Observer } from '../utils/TimerUtil'; 16import TimeUtil from '../utils/TimeUtil'; 17 18/** 19 * 结合单例TimerUtil,实现单例timer组件 20 */ 21@Component 22export default struct ComponentSingletonTimer { 23 @State time: string = '00:00'; 24 private mTextColor: ResourceColor; 25 private mTextSize: Length; 26 private observer: Observer; 27 28 build() { 29 Text(this.time) 30 .id('componentSingletonTimer') 31 .fontColor(this.mTextColor) 32 .fontSize(this.mTextSize) 33 .fontWeight(FontWeight.Regular) 34 .fontFamily('HarmonyOS Sans SC') 35 } 36 37 aboutToAppear() { 38 this.timerCallback(); 39 this.observer = TimerUtil.registerObserver((count: number) => { 40 this.timerCallback(); 41 }) 42 } 43 44 aboutToDisappear() { 45 TimerUtil.removeObserver(this.observer); 46 } 47 48 private timerCallback() { 49 TimerUtil.getTimestamp().then((data) => { 50 this.time = TimeUtil.getTimeStr(data); 51 }); 52 } 53} 54