blob: 760b296274da5a8784e660a98e20f4950f08ec38 [file] [log] [blame]
Paul Stewart0153cf02014-06-02 11:53:36 -07001// 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
Ben Chanc45688b2014-07-02 23:50:45 -07005#ifndef SHILL_PROPERTY_OBSERVER_H_
6#define SHILL_PROPERTY_OBSERVER_H_
Paul Stewart0153cf02014-06-02 11:53:36 -07007
Alex Vakulenko8a532292014-06-16 17:18:44 -07008#include <memory>
Paul Stewart0153cf02014-06-02 11:53:36 -07009
Ben Chancc67c522014-09-03 07:19:18 -070010#include <base/callback.h>
11#include <base/macros.h>
12
Paul Stewart0153cf02014-06-02 11:53:36 -070013#include "shill/accessor_interface.h"
14#include "shill/error.h"
15#include "shill/property_observer_interface.h"
16
17namespace shill {
18
19// A templated object that retains a reference to a typed accessor,
20// and a saved value retrieved from the accessor. When the update
21// method is called, it compares its saved value to the current
22// value returned by the accessor. If the value has changed, it
23// calls the supplied callback and updates the saved value.
24template <class T>
25class PropertyObserver : public PropertyObserverInterface {
26 public:
27 typedef base::Callback<void(const T &new_value)> Callback;
28
Alex Vakulenko8a532292014-06-16 17:18:44 -070029 PropertyObserver(std::shared_ptr<AccessorInterface<T>> accessor,
Paul Stewart0153cf02014-06-02 11:53:36 -070030 Callback callback)
31 : accessor_(accessor), callback_(callback) {
32 Error unused_error;
33 saved_value_ = accessor_->Get(&unused_error);
34 }
Ben Chan5ea763b2014-08-13 11:07:54 -070035 ~PropertyObserver() override {}
Paul Stewart0153cf02014-06-02 11:53:36 -070036
37 // Implements PropertyObserverInterface. Compares the saved value with
38 // what the Get() method of |accessor_| returns. If the value has changed
39 // |callback_| is invoked and |saved_value_| is updated.
Alex Vakulenko016fa0e2014-08-11 15:59:58 -070040 void Update() override {
Paul Stewart0153cf02014-06-02 11:53:36 -070041 Error error;
42 T new_value_ = accessor_->Get(&error);
43 if (!error.IsSuccess() || saved_value_ == new_value_) {
44 return;
45 }
46 callback_.Run(new_value_);
47 saved_value_ = new_value_;
48 }
49
50 private:
51 friend class PropertyObserverTest;
52
Alex Vakulenko8a532292014-06-16 17:18:44 -070053 std::shared_ptr<AccessorInterface<T>> accessor_;
Paul Stewart0153cf02014-06-02 11:53:36 -070054 Callback callback_;
55 T saved_value_;
56
57 DISALLOW_COPY_AND_ASSIGN(PropertyObserver);
58};
59
60} // namespace shill
61
Ben Chanc45688b2014-07-02 23:50:45 -070062#endif // SHILL_PROPERTY_OBSERVER_H_