Paul Stewart | 0153cf0 | 2014-06-02 11:53:36 -0700 | [diff] [blame^] | 1 | // Copyright (c) 2014 The Chromium OS 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 SHILL_PROPERTY_OBSERVER_ |
| 6 | #define SHILL_PROPERTY_OBSERVER_ |
| 7 | |
| 8 | #include <base/basictypes.h> |
| 9 | #include <base/callback.h> |
| 10 | #include <tr1/memory> |
| 11 | |
| 12 | #include "shill/accessor_interface.h" |
| 13 | #include "shill/error.h" |
| 14 | #include "shill/property_observer_interface.h" |
| 15 | |
| 16 | namespace shill { |
| 17 | |
| 18 | // A templated object that retains a reference to a typed accessor, |
| 19 | // and a saved value retrieved from the accessor. When the update |
| 20 | // method is called, it compares its saved value to the current |
| 21 | // value returned by the accessor. If the value has changed, it |
| 22 | // calls the supplied callback and updates the saved value. |
| 23 | template <class T> |
| 24 | class PropertyObserver : public PropertyObserverInterface { |
| 25 | public: |
| 26 | typedef base::Callback<void(const T &new_value)> Callback; |
| 27 | |
| 28 | PropertyObserver(std::tr1::shared_ptr<AccessorInterface<T>> accessor, |
| 29 | Callback callback) |
| 30 | : accessor_(accessor), callback_(callback) { |
| 31 | Error unused_error; |
| 32 | saved_value_ = accessor_->Get(&unused_error); |
| 33 | } |
| 34 | virtual ~PropertyObserver() {} |
| 35 | |
| 36 | // Implements PropertyObserverInterface. Compares the saved value with |
| 37 | // what the Get() method of |accessor_| returns. If the value has changed |
| 38 | // |callback_| is invoked and |saved_value_| is updated. |
| 39 | virtual void Update() override { |
| 40 | Error error; |
| 41 | T new_value_ = accessor_->Get(&error); |
| 42 | if (!error.IsSuccess() || saved_value_ == new_value_) { |
| 43 | return; |
| 44 | } |
| 45 | callback_.Run(new_value_); |
| 46 | saved_value_ = new_value_; |
| 47 | } |
| 48 | |
| 49 | private: |
| 50 | friend class PropertyObserverTest; |
| 51 | |
| 52 | std::tr1::shared_ptr<AccessorInterface<T>> accessor_; |
| 53 | Callback callback_; |
| 54 | T saved_value_; |
| 55 | |
| 56 | DISALLOW_COPY_AND_ASSIGN(PropertyObserver); |
| 57 | }; |
| 58 | |
| 59 | } // namespace shill |
| 60 | |
| 61 | #endif // SHILL_PROPERTY_OBSERVER_ |