• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1  /*
2   * Copyright (c) 2021 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  #include "observer.h"
17  
18  using namespace std;
19  
20  namespace OHOS {
21  
AddObserver(const shared_ptr<Observer> & o)22  void Observable::AddObserver(const shared_ptr<Observer>& o)
23  {
24      if (o == nullptr) {
25          return;
26      }
27  
28      lock_guard<mutex> lock(mutex_);
29      if (obs.count(o) > 0) {
30          return;
31      }
32  
33      obs.insert(o);
34  }
35  
RemoveObserver(const shared_ptr<Observer> & o)36  void Observable::RemoveObserver(const shared_ptr<Observer>& o)
37  {
38      lock_guard<mutex> lock(mutex_);
39      obs.erase(o);
40  }
41  
RemoveAllObservers()42  void Observable::RemoveAllObservers()
43  {
44      lock_guard<mutex> lock(mutex_);
45      obs.clear();
46  }
47  
HasChanged()48  bool Observable::HasChanged()
49  {
50      return changed_;
51  }
52  
GetObserversCount()53  int Observable::GetObserversCount()
54  {
55      lock_guard<mutex> lock(mutex_);
56      return (int)obs.size();
57  }
58  
NotifyObservers()59  void Observable::NotifyObservers()
60  {
61      NotifyObservers(nullptr);
62  }
63  
NotifyObservers(const ObserverArg * arg)64  void Observable::NotifyObservers(const ObserverArg* arg)
65  {
66      set<shared_ptr<Observer>> arrLocal;
67      {
68          lock_guard<mutex> lock(mutex_);
69          if (!changed_) {
70              return;
71          }
72  
73          arrLocal = obs;
74          ClearChanged();
75      }
76  
77      for (auto& o : arrLocal) {
78          o->Update(this, arg);
79      }
80  }
81  
SetChanged()82  void Observable::SetChanged()
83  {
84      changed_ = true;
85  }
86  
ClearChanged()87  void Observable::ClearChanged()
88  {
89      changed_ = false;
90  }
91  
92  }
93