1 // Copyright (C) 2021 The Android Open Source Project 2 // 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 #pragma once 15 16 #include <functional> // for function 17 #include <mutex> // for mutex, lock_guard 18 #include <utility> // for move 19 #include <vector> // for vector 20 21 namespace android { 22 namespace base { 23 24 // An EventNotificationSupport class can be used to add simple notification 25 // support to your class. 26 // 27 // You basically specify an EventObject type, subclass from the support class 28 // and simply call fireEvent when an event needs to be delivered. 29 template <class EventObject> 30 class EventNotificationSupport { 31 using EventListener = 32 std::function<void(const EventObject evt)>; 33 34 public: 35 EventNotificationSupport() = default; 36 addListener(EventListener * listener)37 void addListener(EventListener* listener) { 38 std::lock_guard<std::mutex> lock(mStreamLock); 39 mListeners.push_back(listener); 40 } 41 removeListener(EventListener * listener)42 void removeListener(EventListener* listener) { 43 std::lock_guard<std::mutex> lock(mStreamLock); 44 for (auto it = mListeners.begin(); it != mListeners.end();) { 45 if (*it == listener) { 46 it = mListeners.erase(it); 47 } else { 48 ++it; 49 } 50 } 51 } 52 53 protected: fireEvent(EventObject evt)54 void fireEvent(EventObject evt) { 55 std::lock_guard<std::mutex> lock(mStreamLock); 56 for (const auto& listener : mListeners) { 57 (*listener)(evt); 58 } 59 } 60 61 private: 62 std::vector<EventListener*> mListeners; 63 std::mutex mStreamLock; 64 }; 65 66 // A RaiiEventListener is an event listener that will register and unregister 67 // the provided callback when this object goes out of scope. 68 template <class Source, class EventObject> 69 class RaiiEventListener { 70 public: 71 using EventListener = 72 std::function<void(const EventObject evt)>; 73 RaiiEventListener(Source * src,EventListener listener)74 RaiiEventListener(Source* src, 75 EventListener listener) 76 : mSource(src), mListener(std::move(listener)) { 77 mSource->addListener(&mListener); 78 } 79 ~RaiiEventListener()80 ~RaiiEventListener() { mSource->removeListener(&mListener); } 81 82 private: 83 Source* mSource; 84 EventListener mListener; 85 }; 86 } // namespace base 87 } // namespace android 88