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/logging.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 template <class Source, class Observer>
21 class ScopedObserver {
23 explicit ScopedObserver(Observer* observer) : observer_(observer) {}
29 // Adds the object passed to the constructor as an observer on |source|.
30 void Add(Source* source) {
31 sources_.push_back(source);
32 source->AddObserver(observer_);
35 // Remove the object passed to the constructor as an observer from |source|.
36 void Remove(Source* source) {
37 auto it = std::find(sources_.begin(), sources_.end(), source);
38 DCHECK(it != sources_.end());
40 source->RemoveObserver(observer_);
44 for (size_t i = 0; i < sources_.size(); ++i)
45 sources_[i]->RemoveObserver(observer_);
49 bool IsObserving(Source* source) const {
50 return base::ContainsValue(sources_, source);
53 bool IsObservingSources() const { return !sources_.empty(); }
58 std::vector<Source*> sources_;
60 DISALLOW_COPY_AND_ASSIGN(ScopedObserver);
63 #endif // BASE_SCOPED_OBSERVER_H_