| 6 | #define BASE_SCOPED_OBSERVER_H_ |
| 7 |
| 8 | #include <stddef.h> |
| 9 |
| 10 | #include <algorithm> |
| 11 | #include <vector> |
| 12 |
| 13 | #include "base/logging.h" |
| 14 | #include "base/macros.h" |
| 15 | #include "base/stl_util.h" |
| 16 |
| 17 | // ScopedObserver is used to keep track of the set of sources an object has |
| 18 | // attached itself to as an observer. When ScopedObserver is destroyed it |
| 19 | // removes the object as an observer from all sources it has been added to. |
| 20 | // Basic example (as a member variable): |
| 21 | // |
| 22 | // class MyFooObserver : public FooObserver { |
| 23 | // ... |
| 24 | // private: |
| 25 | // ScopedObserver<Foo, FooObserver> observed_foo_{this}; |
| 26 | // }; |
| 27 | // |
| 28 | // For cases with methods not named AddObserver/RemoveObserver: |
| 29 | // |
| 30 | // class MyFooStateObserver : public FooStateObserver { |
| 31 | // ... |
| 32 | // private: |
| 33 | // ScopedObserver<Foo, |
| 34 | // FooStateObserver, |
| 35 | // &Foo::AddStateObserver, |
| 36 | // &Foo::RemoveStateObserver> |
| 37 | // observed_foo_{this}; |
| 38 | // }; |
| 39 | template <class Source, |
| 40 | class Observer, |
| 41 | void (Source::*AddObsFn)(Observer*) = &Source::AddObserver, |
| 42 | void (Source::*RemoveObsFn)(Observer*) = &Source::RemoveObserver> |
| 43 | class ScopedObserver { |
| 44 | public: |
| 45 | explicit ScopedObserver(Observer* observer) : observer_(observer) {} |
| 46 |
| 47 | ~ScopedObserver() { |
| 48 | RemoveAll(); |
| 49 | } |
| 50 |
| 51 | // Adds the object passed to the constructor as an observer on |source|. |
| 52 | void Add(Source* source) { |
| 53 | sources_.push_back(source); |
| 54 | (source->*AddObsFn)(observer_); |
| 55 | } |
| 56 |
| 57 | // Remove the object passed to the constructor as an observer from |source|. |
| 58 | void Remove(Source* source) { |
| 59 | auto it = std::find(sources_.begin(), sources_.end(), source); |
| 60 | DCHECK(it != sources_.end()); |
| 61 | sources_.erase(it); |
| 62 | (source->*RemoveObsFn)(observer_); |
| 63 | } |
| 64 |
| 65 | void RemoveAll() { |
| 66 | for (size_t i = 0; i < sources_.size(); ++i) |
| 67 | (sources_[i]->*RemoveObsFn)(observer_); |
| 68 | sources_.clear(); |
| 69 | } |
| 70 |
| 71 | bool IsObserving(Source* source) const { |
| 72 | return base::Contains(sources_, source); |
| 73 | } |
| 74 |
| 75 | bool IsObservingSources() const { return !sources_.empty(); } |
| 76 |
| 77 | size_t GetSourcesCount() const { return sources_.size(); } |
| 78 |
| 79 | private: |
| 80 | Observer* observer_; |
| 81 |
| 82 | std::vector<Source*> sources_; |
| 83 |
| 84 | DISALLOW_COPY_AND_ASSIGN(ScopedObserver); |
| 85 | }; |
| 86 |
| 87 | #endif // BASE_SCOPED_OBSERVER_H_ |
| 88 |