1/** 2 * Copyright (c) 2023 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 */ 15import { ContactRepository } from '../../../../../feature/contact'; 16import { HiLog, ArrayUtil } from '../../../../../common'; 17import { ContactVo } from '../model/bean/ContactVo'; 18import WorkerWrapper from "../workers/base/WorkerWrapper"; 19import { DataWorkerConstant } from "../workers/DataWorkerWrapper"; 20import emitter from '@ohos.events.emitter' 21import Constants from '../../../../../common/src/main/ets/Constants'; 22 23const TAG = "ContactsService" 24 25export default class ContactsService { 26 page: number = 0; 27 limit: number = 50; 28 contactList: ContactVo[] = []; 29 context: Context; 30 worker: WorkerWrapper; 31 innerEvent = { 32 eventId: Constants.Event.CONTACTS_CHANGE, 33 priority: emitter.EventPriority.HIGH 34 }; 35 onContactsChange = () => { 36 HiLog.i(TAG, 'onContactsChange refresh'); 37 this.requestItem(); 38 } 39 40 constructor(context: Context, worker: WorkerWrapper) { 41 this.context = context; 42 this.worker = worker; 43 this.requestItem(); 44 ContactRepository.getInstance().registerDataChangeObserver(this.onContactsChange); 45 } 46 47 onDestroy() { 48 ContactRepository.getInstance().unRegisterDataChangeObserver(this.onContactsChange); 49 } 50 51 requestItem() { 52 HiLog.i(TAG, 'Contacts requestItem!'); 53 if (this.page == 0) { 54 this.contactList = []; 55 this.page++; 56 this.refresh(); 57 } else { 58 HiLog.i(TAG, 'isLoading'); 59 } 60 } 61 62 refresh() { 63 let actionData: any = {}; 64 if (this.page == 1) { 65 this.limit = 50; 66 } else { 67 this.limit = 500; 68 } 69 actionData.page = this.page; 70 actionData.limit = this.limit; 71 this.worker.sendRequest(DataWorkerConstant[DataWorkerConstant.getAllContact], { 72 actionData: actionData, 73 context: this.context 74 }, (result) => { 75 HiLog.i(TAG, 'getAllContact and refresh, length is: ' + JSON.stringify(result.length)); 76 if (!ArrayUtil.isEmpty(result)) { 77 this.contactList = this.contactList.concat(result); 78 } 79 const contactCount = result.length; 80 AppStorage.SetOrCreate<ContactVo[]>('contactList', this.contactList); 81 emitter.emit(this.innerEvent); 82 if (contactCount < this.limit) { 83 this.page = 0; 84 HiLog.i(TAG, 'Contacts load completed: ' + JSON.stringify(this.contactList.length)); 85 } else { 86 this.page++; 87 setTimeout(() => { 88 this.refresh(); 89 }, this.page == 2 ? 700 : 1); 90 } 91 }) 92 } 93}