blob: 7f1d6fba96a6b741e5929d5226d36c13f1c9e080 [file] [log] [blame]
[email protected]5924a0b2012-04-27 17:02:281// 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.
4
[email protected]28f57b32012-06-22 21:47:305#ifndef BASE_SCOPED_OBSERVER_H_
6#define BASE_SCOPED_OBSERVER_H_
[email protected]5924a0b2012-04-27 17:02:287
avi9b6f42932015-12-26 22:15:148#include <stddef.h>
9
[email protected]5924a0b2012-04-27 17:02:2810#include <algorithm>
11#include <vector>
12
scheibcc12a6a2014-10-27 22:17:3213#include "base/logging.h"
avi9b6f42932015-12-26 22:15:1414#include "base/macros.h"
thestig6c335d42015-12-07 18:25:3415#include "base/stl_util.h"
[email protected]5924a0b2012-04-27 17:02:2816
[email protected]5924a0b2012-04-27 17:02:2817// 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.
20template <class Source, class Observer>
21class ScopedObserver {
22 public:
23 explicit ScopedObserver(Observer* observer) : observer_(observer) {}
24
25 ~ScopedObserver() {
[email protected]50703fc2014-04-08 04:01:0626 RemoveAll();
[email protected]5924a0b2012-04-27 17:02:2827 }
28
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_);
33 }
34
[email protected]d725b2c2012-10-05 16:01:5735 // Remove the object passed to the constructor as an observer from |source|.
[email protected]5924a0b2012-04-27 17:02:2836 void Remove(Source* source) {
scheibcc12a6a2014-10-27 22:17:3237 auto it = std::find(sources_.begin(), sources_.end(), source);
38 DCHECK(it != sources_.end());
39 sources_.erase(it);
[email protected]5924a0b2012-04-27 17:02:2840 source->RemoveObserver(observer_);
41 }
42
[email protected]50703fc2014-04-08 04:01:0643 void RemoveAll() {
44 for (size_t i = 0; i < sources_.size(); ++i)
45 sources_[i]->RemoveObserver(observer_);
46 sources_.clear();
47 }
48
[email protected]d725b2c2012-10-05 16:01:5749 bool IsObserving(Source* source) const {
skyostil52f72dda2016-08-12 19:44:4950 return base::ContainsValue(sources_, source);
[email protected]d725b2c2012-10-05 16:01:5751 }
52
hanxi9bd85fa2015-05-05 19:55:0053 bool IsObservingSources() const { return !sources_.empty(); }
54
[email protected]5924a0b2012-04-27 17:02:2855 private:
56 Observer* observer_;
57
58 std::vector<Source*> sources_;
59
60 DISALLOW_COPY_AND_ASSIGN(ScopedObserver);
61};
62
[email protected]28f57b32012-06-22 21:47:3063#endif // BASE_SCOPED_OBSERVER_H_