blob: 94bac81603a98381bd01a41c9beb13792dc1b2fb [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
8#include <base/basictypes.h>
9#include <base/callback.h>
Alex Vakulenko8a532292014-06-16 17:18:44 -070010#include <memory>
Paul Stewart0153cf02014-06-02 11:53:36 -070011
12#include "shill/accessor_interface.h"
13#include "shill/error.h"
14#include "shill/property_observer_interface.h"
15
16namespace 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.
23template <class T>
24class PropertyObserver : public PropertyObserverInterface {
25 public:
26 typedef base::Callback<void(const T &new_value)> Callback;
27
Alex Vakulenko8a532292014-06-16 17:18:44 -070028 PropertyObserver(std::shared_ptr<AccessorInterface<T>> accessor,
Paul Stewart0153cf02014-06-02 11:53:36 -070029 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
Alex Vakulenko8a532292014-06-16 17:18:44 -070052 std::shared_ptr<AccessorInterface<T>> accessor_;
Paul Stewart0153cf02014-06-02 11:53:36 -070053 Callback callback_;
54 T saved_value_;
55
56 DISALLOW_COPY_AND_ASSIGN(PropertyObserver);
57};
58
59} // namespace shill
60
Ben Chanc45688b2014-07-02 23:50:45 -070061#endif // SHILL_PROPERTY_OBSERVER_H_