notifier.h (2143B)
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 #include "rtc_base/thread_annotations.h" 21 22 namespace webrtc { 23 24 // Implements a template version of a notifier. 25 // TODO(deadbeef): This is an implementation detail; move out of api/. 26 template <class T> 27 class Notifier : public T { 28 public: 29 Notifier() = default; 30 31 virtual void RegisterObserver(ObserverInterface* observer) { 32 RTC_DCHECK_RUN_ON(&sequence_checker_); 33 RTC_DCHECK(observer != nullptr); 34 observers_.push_back(observer); 35 } 36 37 virtual void UnregisterObserver(ObserverInterface* observer) { 38 RTC_DCHECK_RUN_ON(&sequence_checker_); 39 for (std::list<ObserverInterface*>::iterator it = observers_.begin(); 40 it != observers_.end(); it++) { 41 if (*it == observer) { 42 observers_.erase(it); 43 break; 44 } 45 } 46 } 47 48 void FireOnChanged() { 49 RTC_DCHECK_RUN_ON(&sequence_checker_); 50 // Copy the list of observers to avoid a crash if the observer object 51 // unregisters as a result of the OnChanged() call. If the same list is used 52 // UnregisterObserver will affect the list make the iterator invalid. 53 std::list<ObserverInterface*> observers = observers_; 54 for (std::list<ObserverInterface*>::iterator it = observers.begin(); 55 it != observers.end(); ++it) { 56 (*it)->OnChanged(); 57 } 58 } 59 60 protected: 61 std::list<ObserverInterface*> observers_ RTC_GUARDED_BY(sequence_checker_); 62 63 private: 64 RTC_NO_UNIQUE_ADDRESS SequenceChecker sequence_checker_{ 65 SequenceChecker::kDetached}; 66 }; 67 68 } // namespace webrtc 69 70 #endif // API_NOTIFIER_H_