1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef BASE_SCOPED_OBSERVER_H_
6 #define BASE_SCOPED_OBSERVER_H_
13 #include "base/check.h"
14 #include "base/macros.h"
15 #include "base/stl_util.h"
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):
22 // class MyFooObserver : public FooObserver {
25 // ScopedObserver<Foo, FooObserver> observed_foo_{this};
28 // For cases with methods not named AddObserver/RemoveObserver:
30 // class MyFooStateObserver : public FooStateObserver {
33 // ScopedObserver<Foo,
35 // &Foo::AddStateObserver,
36 // &Foo::RemoveStateObserver>
37 // observed_foo_{this};
39 template <class Source,
41 void (Source::*AddObsFn)(Observer*) = &Source::AddObserver,
42 void (Source::*RemoveObsFn)(Observer*) = &Source::RemoveObserver>
43 class ScopedObserver {
45 explicit ScopedObserver(Observer* observer) : observer_(observer) {}
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_);
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());
62 (source->*RemoveObsFn)(observer_);
66 for (size_t i = 0; i < sources_.size(); ++i)
67 (sources_[i]->*RemoveObsFn)(observer_);
71 bool IsObserving(Source* source) const {
72 return base::Contains(sources_, source);
75 bool IsObservingSources() const { return !sources_.empty(); }
77 size_t GetSourcesCount() const { return sources_.size(); }
82 std::vector<Source*> sources_;
84 DISALLOW_COPY_AND_ASSIGN(ScopedObserver);
87 #endif // BASE_SCOPED_OBSERVER_H_