1 // Copyright 2010 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef COMPONENTS_PREFS_PREF_CHANGE_REGISTRAR_H_
6 #define COMPONENTS_PREFS_PREF_CHANGE_REGISTRAR_H_
11 #include "base/functional/callback.h"
12 #include "base/memory/raw_ptr.h"
13 #include "components/prefs/pref_observer.h"
14 #include "components/prefs/prefs_export.h"
18 // Automatically manages the registration of one or more pref change observers
19 // with a PrefStore. Functions much like NotificationRegistrar, but specifically
20 // manages observers of preference changes. When the Registrar is destroyed,
21 // all registered observers are automatically unregistered with the PrefStore.
22 class COMPONENTS_PREFS_EXPORT PrefChangeRegistrar final : public PrefObserver {
24 // You can register this type of callback if you need to know the
25 // path of the preference that is changing.
26 using NamedChangeCallback = base::RepeatingCallback<void(const std::string&)>;
28 PrefChangeRegistrar();
30 PrefChangeRegistrar(const PrefChangeRegistrar&) = delete;
31 PrefChangeRegistrar& operator=(const PrefChangeRegistrar&) = delete;
33 ~PrefChangeRegistrar();
35 // Must be called before adding or removing observers. Can be called more
36 // than once as long as the value of |service| doesn't change.
37 void Init(PrefService* service);
39 // Adds a pref observer for the specified pref |path| and |obs| observer
40 // object. All registered observers will be automatically unregistered
41 // when the registrar's destructor is called.
43 // The second version binds a callback that will receive the path of
44 // the preference that is changing as its parameter.
46 // Only one observer may be registered per path.
47 void Add(const std::string& path, const base::RepeatingClosure& obs);
48 void Add(const std::string& path, const NamedChangeCallback& obs);
50 // Removes the pref observer registered for |path|.
51 void Remove(const std::string& path);
53 // Removes all observers that have been previously added with a call to Add.
56 // Returns true if no pref observers are registered.
59 // Check whether |pref| is in the set of preferences being observed.
60 bool IsObserved(const std::string& pref);
62 // Return the PrefService for this registrar.
64 const PrefService* prefs() const;
68 void OnPreferenceChanged(PrefService* service,
69 const std::string& pref_name) override;
71 static void InvokeUnnamedCallback(const base::RepeatingClosure& callback,
72 const std::string& pref_name);
74 using ObserverMap = std::map<std::string, NamedChangeCallback>;
76 ObserverMap observers_;
77 raw_ptr<PrefService, AcrossTasksDanglingUntriaged> service_;
80 #endif // COMPONENTS_PREFS_PREF_CHANGE_REGISTRAR_H_