1 // Copyright 2011 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_NOTIFIER_IMPL_H_
6 #define COMPONENTS_PREFS_PREF_NOTIFIER_IMPL_H_
11 #include <unordered_map>
13 #include "base/compiler_specific.h"
14 #include "base/functional/callback.h"
15 #include "base/memory/raw_ptr.h"
16 #include "base/observer_list.h"
17 #include "base/sequence_checker.h"
18 #include "components/prefs/pref_notifier.h"
19 #include "components/prefs/pref_observer.h"
20 #include "components/prefs/prefs_export.h"
24 // The PrefNotifier implementation used by the PrefService.
25 class COMPONENTS_PREFS_EXPORT PrefNotifierImpl : public PrefNotifier {
28 explicit PrefNotifierImpl(PrefService* pref_service);
30 PrefNotifierImpl(const PrefNotifierImpl&) = delete;
31 PrefNotifierImpl& operator=(const PrefNotifierImpl&) = delete;
33 ~PrefNotifierImpl() override;
35 // If the pref at the given path changes, we call the observer's
36 // OnPreferenceChanged method.
37 void AddPrefObserver(const std::string& path, PrefObserver* observer);
38 void RemovePrefObserver(const std::string& path, PrefObserver* observer);
40 // These observers are called for any pref changes.
42 // AVOID ADDING THESE. See the long comment in the identically-named
43 // functions on PrefService for background.
44 void AddPrefObserverAllPrefs(PrefObserver* observer);
45 void RemovePrefObserverAllPrefs(PrefObserver* observer);
47 // We run the callback once, when initialization completes. The bool
48 // parameter will be set to true for successful initialization,
49 // false for unsuccessful.
50 void AddInitObserver(base::OnceCallback<void(bool)> observer);
52 void SetPrefService(PrefService* pref_service);
54 // PrefNotifier overrides.
55 void OnPreferenceChanged(const std::string& pref_name) override;
58 // PrefNotifier overrides.
59 void OnInitializationCompleted(bool succeeded) override;
61 // A map from pref names to a list of observers. Observers get fired in the
62 // order they are added. These should only be accessed externally for unit
64 typedef base::ObserverList<PrefObserver>::Unchecked PrefObserverList;
65 typedef std::unordered_map<std::string, std::unique_ptr<PrefObserverList>>
68 typedef std::list<base::OnceCallback<void(bool)>> PrefInitObserverList;
70 const PrefObserverMap* pref_observers() const { return &pref_observers_; }
73 // For the given pref_name, fire any observer of the pref. Virtual so it can
74 // be mocked for unit testing.
75 virtual void FireObservers(const std::string& path);
77 // Weak reference; the notifier is owned by the PrefService.
78 raw_ptr<PrefService> pref_service_;
80 PrefObserverMap pref_observers_;
81 PrefInitObserverList init_observers_;
83 // Observers for changes to any preference.
84 PrefObserverList all_prefs_pref_observers_;
86 SEQUENCE_CHECKER(sequence_checker_);
89 #endif // COMPONENTS_PREFS_PREF_NOTIFIER_IMPL_H_