xref: /aosp_15_r20/external/webrtc/api/notifier.h (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright 2011 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #ifndef API_NOTIFIER_H_
12 #define API_NOTIFIER_H_
13 
14 #include <list>
15 
16 #include "api/media_stream_interface.h"
17 #include "api/sequence_checker.h"
18 #include "rtc_base/checks.h"
19 #include "rtc_base/system/no_unique_address.h"
20 
21 namespace webrtc {
22 
23 // Implements a template version of a notifier.
24 // TODO(deadbeef): This is an implementation detail; move out of api/.
25 template <class T>
26 class Notifier : public T {
27  public:
Notifier()28   Notifier() { sequence_checker_.Detach(); }
29 
RegisterObserver(ObserverInterface * observer)30   virtual void RegisterObserver(ObserverInterface* observer) {
31     RTC_DCHECK_RUN_ON(&sequence_checker_);
32     RTC_DCHECK(observer != nullptr);
33     observers_.push_back(observer);
34   }
35 
UnregisterObserver(ObserverInterface * observer)36   virtual void UnregisterObserver(ObserverInterface* observer) {
37     RTC_DCHECK_RUN_ON(&sequence_checker_);
38     for (std::list<ObserverInterface*>::iterator it = observers_.begin();
39          it != observers_.end(); it++) {
40       if (*it == observer) {
41         observers_.erase(it);
42         break;
43       }
44     }
45   }
46 
FireOnChanged()47   void FireOnChanged() {
48     RTC_DCHECK_RUN_ON(&sequence_checker_);
49     // Copy the list of observers to avoid a crash if the observer object
50     // unregisters as a result of the OnChanged() call. If the same list is used
51     // UnregisterObserver will affect the list make the iterator invalid.
52     std::list<ObserverInterface*> observers = observers_;
53     for (std::list<ObserverInterface*>::iterator it = observers.begin();
54          it != observers.end(); ++it) {
55       (*it)->OnChanged();
56     }
57   }
58 
59  protected:
60   std::list<ObserverInterface*> observers_ RTC_GUARDED_BY(sequence_checker_);
61 
62  private:
63   RTC_NO_UNIQUE_ADDRESS SequenceChecker sequence_checker_;
64 };
65 
66 }  // namespace webrtc
67 
68 #endif  // API_NOTIFIER_H_
69