1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.car.internal; 18 19 import java.util.Collection; 20 import java.util.Collections; 21 import java.util.HashMap; 22 import java.util.Map; 23 24 /** 25 * Represent listeners for a sensor grouped by their rate. 26 * 27 * @param <EventListenerType> type of event listener 28 * @hide 29 */ 30 public class CarRatedListeners<EventListenerType> { 31 private final Map<EventListenerType, Integer> mListenersToRate = new HashMap<>(4); 32 33 private int mUpdateRate; 34 35 protected long mLastUpdateTime = -1; 36 CarRatedListeners(int rate)37 protected CarRatedListeners(int rate) { 38 mUpdateRate = rate; 39 } 40 41 /** Returns true if it contains the listener passed as parameter. */ contains(EventListenerType listener)42 public boolean contains(EventListenerType listener) { 43 return mListenersToRate.containsKey(listener); 44 } 45 getRate()46 public int getRate() { 47 return mUpdateRate; 48 } 49 50 /** 51 * Remove given listener from the list and update rate if necessary. 52 * 53 * @param listener 54 * @return true if rate was updated. Otherwise, returns false. 55 */ remove(EventListenerType listener)56 public boolean remove(EventListenerType listener) { 57 mListenersToRate.remove(listener); 58 if (mListenersToRate.isEmpty()) { 59 return false; 60 } 61 Integer updateRate = Collections.min(mListenersToRate.values()); 62 if (updateRate != mUpdateRate) { 63 mUpdateRate = updateRate; 64 return true; 65 } 66 return false; 67 } 68 isEmpty()69 public boolean isEmpty() { 70 return mListenersToRate.isEmpty(); 71 } 72 73 /** 74 * Add given listener to the list and update rate if necessary. 75 * 76 * @param listener if null, add part is skipped. 77 * @param updateRate 78 * @return true if rate was updated. Otherwise, returns false. 79 */ addAndUpdateRate(EventListenerType listener, int updateRate)80 public boolean addAndUpdateRate(EventListenerType listener, int updateRate) { 81 Integer oldUpdateRate = mListenersToRate.put(listener, updateRate); 82 if (mUpdateRate > updateRate) { 83 mUpdateRate = updateRate; 84 return true; 85 } else if (oldUpdateRate != null && oldUpdateRate == mUpdateRate) { 86 mUpdateRate = Collections.min(mListenersToRate.values()); 87 } 88 return false; 89 } 90 getListeners()91 public Collection<EventListenerType> getListeners() { 92 return mListenersToRate.keySet(); 93 } 94 } 95