17 #ifndef KAA_OBSERVER_KAAOBSERVABLE_HPP_
18 #define KAA_OBSERVER_KAAOBSERVABLE_HPP_
21 #include <unordered_map>
22 #include <unordered_set>
30 template<
class Signature,
class Key,
class Function = std::function<Signature>>
41 auto it = slots_.find(key);
42 if (it != slots_.end() && !it->second.isRemoved()) {
45 slotsToRemove_.erase(key);
46 slotsToAdd_.insert(std::make_pair(key, CallbackWrapper(f)));
50 return slots_.insert(std::make_pair(key, CallbackWrapper(f))).second;
58 slotsToAdd_.erase(key);
59 slotsToRemove_.insert(key);
61 auto it = slots_.find(key);
62 if (it != slots_.end()) {
71 template <
typename... Args>
76 for (
auto& pair : slots_) {
77 pair.second(std::forward<Args>(args)...);
82 for (
auto it = slotsToAdd_.begin(); it != slotsToAdd_.end(); ++it) {
83 slots_[it->first] = it->second;
87 for (
auto key : slotsToRemove_) {
90 slotsToRemove_.clear();
97 return slots_.empty() && slotsToAdd_.empty();
101 class CallbackWrapper
104 CallbackWrapper() : isRemoved_(false) { }
105 CallbackWrapper(
const Function& f) : callback_(f), isRemoved_(false) { }
106 CallbackWrapper(
const CallbackWrapper& o) : callback_(o.callback_), isRemoved_((bool) o.isRemoved_) { }
107 CallbackWrapper(CallbackWrapper&& o) : callback_(std::move(o.callback_)), isRemoved_((bool) o.isRemoved_) { }
108 CallbackWrapper& operator=(
const CallbackWrapper& o) { callback_ = o.callback_; isRemoved_ = (bool) o.isRemoved_;
return *
this; }
109 CallbackWrapper& operator=(CallbackWrapper&& o) { callback_ = std::move(o.callback_); isRemoved_ = (bool) o.isRemoved_;
return *
this; }
111 template <
typename... Args>
115 callback_(std::forward<Args>(args)...);
119 bool isRemoved()
const {
return isRemoved_; }
120 void remove() { isRemoved_ =
true; }
127 std::unordered_map<Key, CallbackWrapper> slots_;
128 std::unordered_map<Key, CallbackWrapper> slotsToAdd_;
129 std::unordered_set<Key> slotsToRemove_;
133 KAA_MUTEX_DECLARE(mainGuard_);
134 KAA_MUTEX_DECLARE(modificationGuard_);
void operator()(Args &&...args)
void removeCallback(const Key &key)
#define KAA_MUTEX_UNIQUE_DECLARE(name, mtx)
bool addCallback(const Key &key, const Function &f)