blob: 79bcec5f44f12016225332b402d72545523a1643 [file] [log] [blame]
Vitaly Bukacbed2062015-08-17 12:54:05 -07001// 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
5#ifndef BASE_SCOPED_OBSERVER_H_
6#define BASE_SCOPED_OBSERVER_H_
7
Alex Vakulenko674f0eb2016-01-20 08:10:48 -08008#include <stddef.h>
9
Vitaly Bukacbed2062015-08-17 12:54:05 -070010#include <algorithm>
11#include <vector>
12
Vitaly Bukacbed2062015-08-17 12:54:05 -070013#include "base/logging.h"
Alex Vakulenko674f0eb2016-01-20 08:10:48 -080014#include "base/macros.h"
Vitaly Bukacbed2062015-08-17 12:54:05 -070015
16// ScopedObserver is used to keep track of the set of sources an object has
17// attached itself to as an observer. When ScopedObserver is destroyed it
18// removes the object as an observer from all sources it has been added to.
19template <class Source, class Observer>
20class ScopedObserver {
21 public:
22 explicit ScopedObserver(Observer* observer) : observer_(observer) {}
23
24 ~ScopedObserver() {
25 RemoveAll();
26 }
27
28 // Adds the object passed to the constructor as an observer on |source|.
29 void Add(Source* source) {
30 sources_.push_back(source);
31 source->AddObserver(observer_);
32 }
33
34 // Remove the object passed to the constructor as an observer from |source|.
35 void Remove(Source* source) {
36 auto it = std::find(sources_.begin(), sources_.end(), source);
37 DCHECK(it != sources_.end());
38 sources_.erase(it);
39 source->RemoveObserver(observer_);
40 }
41
42 void RemoveAll() {
43 for (size_t i = 0; i < sources_.size(); ++i)
44 sources_[i]->RemoveObserver(observer_);
45 sources_.clear();
46 }
47
48 bool IsObserving(Source* source) const {
Alex Vakulenko674f0eb2016-01-20 08:10:48 -080049 return ContainsValue(sources_, source);
Vitaly Bukacbed2062015-08-17 12:54:05 -070050 }
51
52 bool IsObservingSources() const { return !sources_.empty(); }
53
54 private:
55 Observer* observer_;
56
57 std::vector<Source*> sources_;
58
59 DISALLOW_COPY_AND_ASSIGN(ScopedObserver);
60};
61
62#endif // BASE_SCOPED_OBSERVER_H_