1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef HIVIEW_BASE_EVENT_EXPORT_SETTING_OBSERVER_MGR_H
17 #define HIVIEW_BASE_EVENT_EXPORT_SETTING_OBSERVER_MGR_H
18 
19 #include <mutex>
20 #include <string>
21 #include <unordered_map>
22 
23 #include "data_ability_observer_stub.h"
24 #include "singleton.h"
25 #include "uri.h"
26 
27 namespace OHOS {
28 namespace HiviewDFX {
29 class SettingObserver : public AAFwk::DataAbilityObserverStub {
30 public:
31     using ObserverCallback = std::function<void(const std::string&)>;
SettingObserver(const std::string & paramKey,ObserverCallback callback)32     SettingObserver(const std::string& paramKey, ObserverCallback callback)
33         : paramKey_(paramKey), callback_(callback) {}
34     ~SettingObserver() = default;
35 
36     void OnChange();
37 
38 private:
39     std::string paramKey_;
40     ObserverCallback callback_;
41 };
42 
43 class SettingObserverManager : public DelayedSingleton<SettingObserverManager> {
44 DECLARE_DELAYED_SINGLETON(SettingObserverManager);
45 public:
46     bool RegisterObserver(const std::string& paramKey, SettingObserver::ObserverCallback callback);
47     bool UnregisterObserver(const std::string& paramKey);
48     std::string GetStringValue(const std::string& paramKey, const std::string& defaultVal = "");
49 
50 private:
51     Uri AssembleUri(const std::string& paramKey);
52     sptr<SettingObserver> GetSettingObserver(const std::string& paramKey);
53 
54 private:
55     std::unordered_map<std::string, sptr<SettingObserver>> observers_;
56     std::mutex observersMutex_;
57 };
58 } // namespace HiviewDFX
59 } // namespace OHOS
60 
61 #endif // HIVIEW_BASE_EVENT_EXPORT_SETTING_OBSERVER_MGR_H