1 /* 2 * Copyright 2019 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 #pragma once 18 19 #include <utility> 20 #include "base/callback_list.h" 21 #include "os/handler.h" 22 23 /* This file contains CallbackList implementation that will execute callback on provided Handler thread 24 25 Example usage inside your class: 26 27 private: 28 common::CallbackList<void(int)> callbacks_list_; 29 public: 30 std::unique_ptr<common::CallbackList<void(int)>::Subscription> RegisterCallback( 31 const base::RepeatingCallback<void(int)>& cb, os::Handler* handler) { 32 return callbacks_list_.Add({cb, handler}); 33 } 34 35 void NotifyAllCallbacks(int value) { 36 callbacks_list_.Notify(value); 37 } 38 */ 39 40 namespace bluetooth { 41 namespace common { 42 43 namespace { 44 template <typename CallbackType> 45 struct CallbackWithHandler { CallbackWithHandlerCallbackWithHandler46 CallbackWithHandler(base::RepeatingCallback<CallbackType> callback, os::Handler* handler) 47 : callback(callback), handler(handler) {} 48 is_nullCallbackWithHandler49 bool is_null() const { 50 return callback.is_null(); 51 } 52 ResetCallbackWithHandler53 void Reset() { 54 callback.Reset(); 55 } 56 57 base::RepeatingCallback<CallbackType> callback; 58 os::Handler* handler; 59 }; 60 61 } // namespace 62 63 template <typename Sig> 64 class CallbackList; 65 template <typename... Args> 66 class CallbackList<void(Args...)> : public base::internal::CallbackListBase<CallbackWithHandler<void(Args...)>> { 67 public: 68 using CallbackType = CallbackWithHandler<void(Args...)>; 69 CallbackList() = default; 70 template <typename... RunArgs> Notify(RunArgs &&...args)71 void Notify(RunArgs&&... args) { 72 auto it = this->GetIterator(); 73 CallbackType* cb; 74 while ((cb = it.GetNext()) != nullptr) { 75 cb->handler->Post(base::Bind(cb->callback, args...)); 76 } 77 } 78 79 private: 80 DISALLOW_COPY_AND_ASSIGN(CallbackList); 81 }; 82 83 } // namespace common 84 } // namespace bluetooth 85