1 /*
2  * Copyright (c) 2023 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 #ifndef UPDATER_EVENT_H
16 #define UPDATER_EVENT_H
17 
18 #include <functional>
19 #include <string>
20 #include <map>
21 #include <mutex>
22 #include <vector>
23 
24 #include "event_id.h"
25 
26 namespace Updater {
27 class UpdaterEvent {
28     using EventHandler = std::function<void()>;
29 public:
Subscribe(enum EventId id,EventHandler handler)30     static void Subscribe(enum EventId id, EventHandler handler)
31     {
32         std::unique_lock<std::mutex> lock(mutex_);
33         eventMap_[id].push_back(handler);
34     }
Invoke(enum EventId id)35     static void Invoke(enum EventId id)
36     {
37         std::unique_lock<std::mutex> lock(mutex_);
38         for (const auto &handler : eventMap_[id]) {
39             if (handler != nullptr) {
40                 handler();
41             }
42         }
43     }
44 private:
45     static inline std::mutex mutex_ {};
46     static inline std::map<enum EventId, std::vector<EventHandler>> eventMap_ {};
47 };
48 } // Updater
49 #endif // UPDATER_EVENT_H