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 * @hide 27 */ 28 public class CarRatedListeners<EventListenerType> { 29 private final Map<EventListenerType, Integer> mListenersToRate = new HashMap<>(4); 30 31 private int mUpdateRate; 32 33 protected long mLastUpdateTime = -1; 34 35 protected CarRatedListeners(int rate) { 36 mUpdateRate = rate; 37 } 38 39 public boolean contains(EventListenerType listener) { 40 return mListenersToRate.containsKey(listener); 41 } 42 43 public int getRate() { 44 return mUpdateRate; 45 } 46 47 /** 48 * Remove given listener from the list and update rate if necessary. 49 * 50 * @param listener 51 * @return true if rate was updated. Otherwise, returns false. 52 */ 53 public boolean remove(EventListenerType listener) { 54 mListenersToRate.remove(listener); 55 if (mListenersToRate.isEmpty()) { 56 return false; 57 } 58 Integer updateRate = Collections.min(mListenersToRate.values()); 59 if (updateRate != mUpdateRate) { 60 mUpdateRate = updateRate; 61 return true; 62 } 63 return false; 64 } 65 66 public boolean isEmpty() { 67 return mListenersToRate.isEmpty(); 68 } 69 70 /** 71 * Add given listener to the list and update rate if necessary. 72 * 73 * @param listener if null, add part is skipped. 74 * @param updateRate 75 * @return true if rate was updated. Otherwise, returns false. 76 */ 77 public boolean addAndUpdateRate(EventListenerType listener, int updateRate) { 78 Integer oldUpdateRate = mListenersToRate.put(listener, updateRate); 79 if (mUpdateRate > updateRate) { 80 mUpdateRate = updateRate; 81 return true; 82 } else if (oldUpdateRate != null && oldUpdateRate == mUpdateRate) { 83 mUpdateRate = Collections.min(mListenersToRate.values()); 84 } 85 return false; 86 } 87 88 public Collection<EventListenerType> getListeners() { 89 return mListenersToRate.keySet(); 90 } 91 } 92