Home | History | Annotate | Download | only in base
      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 <stddef.h>
      9 
     10 #include <algorithm>
     11 #include <vector>
     12 
     13 #include "base/logging.h"
     14 #include "base/macros.h"
     15 #include "base/stl_util.h"
     16 
     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 {
     22  public:
     23   explicit ScopedObserver(Observer* observer) : observer_(observer) {}
     24 
     25   ~ScopedObserver() {
     26     RemoveAll();
     27   }
     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 
     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());
     39     sources_.erase(it);
     40     source->RemoveObserver(observer_);
     41   }
     42 
     43   void RemoveAll() {
     44     for (size_t i = 0; i < sources_.size(); ++i)
     45       sources_[i]->RemoveObserver(observer_);
     46     sources_.clear();
     47   }
     48 
     49   bool IsObserving(Source* source) const {
     50     return base::ContainsValue(sources_, source);
     51   }
     52 
     53   bool IsObservingSources() const { return !sources_.empty(); }
     54 
     55  private:
     56   Observer* observer_;
     57 
     58   std::vector<Source*> sources_;
     59 
     60   DISALLOW_COPY_AND_ASSIGN(ScopedObserver);
     61 };
     62 
     63 #endif  // BASE_SCOPED_OBSERVER_H_
     64