Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(439)

Side by Side Diff: base/scoped_observer.h

Issue 1647803004: Move base to DEPS (Closed) Base URL: git@github.com:domokit/mojo.git@master
Patch Set: Created 4 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « base/scoped_native_library_unittest.cc ('k') | base/security_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
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.
4
5 #ifndef BASE_SCOPED_OBSERVER_H_
6 #define BASE_SCOPED_OBSERVER_H_
7
8 #include <algorithm>
9 #include <vector>
10
11 #include "base/basictypes.h"
12 #include "base/logging.h"
13
14 // ScopedObserver is used to keep track of the set of sources an object has
15 // attached itself to as an observer. When ScopedObserver is destroyed it
16 // removes the object as an observer from all sources it has been added to.
17 template <class Source, class Observer>
18 class ScopedObserver {
19 public:
20 explicit ScopedObserver(Observer* observer) : observer_(observer) {}
21
22 ~ScopedObserver() {
23 RemoveAll();
24 }
25
26 // Adds the object passed to the constructor as an observer on |source|.
27 void Add(Source* source) {
28 sources_.push_back(source);
29 source->AddObserver(observer_);
30 }
31
32 // Remove the object passed to the constructor as an observer from |source|.
33 void Remove(Source* source) {
34 auto it = std::find(sources_.begin(), sources_.end(), source);
35 DCHECK(it != sources_.end());
36 sources_.erase(it);
37 source->RemoveObserver(observer_);
38 }
39
40 void RemoveAll() {
41 for (size_t i = 0; i < sources_.size(); ++i)
42 sources_[i]->RemoveObserver(observer_);
43 sources_.clear();
44 }
45
46 bool IsObserving(Source* source) const {
47 return std::find(sources_.begin(), sources_.end(), source) !=
48 sources_.end();
49 }
50
51 bool IsObservingSources() const { return !sources_.empty(); }
52
53 private:
54 Observer* observer_;
55
56 std::vector<Source*> sources_;
57
58 DISALLOW_COPY_AND_ASSIGN(ScopedObserver);
59 };
60
61 #endif // BASE_SCOPED_OBSERVER_H_
OLDNEW
« no previous file with comments | « base/scoped_native_library_unittest.cc ('k') | base/security_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698