Make Observer to be able to observe multiple Observables. (#1234)

* Make Observer to be able to observe multiple Observables.

* Fix Observer destructor cleanup.

Co-authored-by: Sacha Weatherstone <sachaw100@hotmail.com>
raytac-diy
Balázs Kelemen 2022-04-14 00:43:06 +02:00 zatwierdzone przez GitHub
rodzic f511baba9a
commit b76424db50
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: 4AEE18F83AFDEB23
3 zmienionych plików z 15 dodań i 15 usunięć

Wyświetl plik

@ -11,13 +11,13 @@ template <class T> class Observable;
*/ */
template <class T> class Observer template <class T> class Observer
{ {
Observable<T> *observed = NULL; std::list<Observable<T> *> observed;
public: public:
virtual ~Observer(); virtual ~Observer();
/// Stop watching our current obserable /// Stop watching the obserable
void unobserve(); void unobserve(Observable<T> *o);
/// Start watching a specified observable /// Start watching a specified observable
void observe(Observable<T> *o); void observe(Observable<T> *o);
@ -87,21 +87,21 @@ template <class T> class Observable
template <class T> Observer<T>::~Observer() template <class T> Observer<T>::~Observer()
{ {
unobserve(); for (typename std::list<Observable<T> *>::const_iterator iterator = observed.begin(); iterator != observed.end();
++iterator) {
(*iterator)->removeObserver(this);
}
observed.clear();
} }
template <class T> void Observer<T>::unobserve() template <class T> void Observer<T>::unobserve(Observable<T> *o)
{ {
if (observed) o->removeObserver(this);
observed->removeObserver(this); observed.remove(o);
observed = NULL;
} }
template <class T> void Observer<T>::observe(Observable<T> *o) template <class T> void Observer<T>::observe(Observable<T> *o)
{ {
// We can only watch one thing at a time observed.push_back(o);
assert(!observed);
observed = o;
o->addObserver(this); o->addObserver(this);
} }

Wyświetl plik

@ -95,8 +95,8 @@ bool GPS::setup()
GPS::~GPS() GPS::~GPS()
{ {
// we really should unregister our sleep observer // we really should unregister our sleep observer
notifySleepObserver.unobserve(); notifySleepObserver.unobserve(&notifySleep);
notifyDeepSleepObserver.unobserve(); notifyDeepSleepObserver.unobserve(&notifyDeepSleep);
} }
bool GPS::hasLock() { return hasValidLocation; } bool GPS::hasLock() { return hasValidLocation; }

Wyświetl plik

@ -48,7 +48,7 @@ void PhoneAPI::close()
if (state != STATE_SEND_NOTHING) { if (state != STATE_SEND_NOTHING) {
state = STATE_SEND_NOTHING; state = STATE_SEND_NOTHING;
unobserve(); unobserve(&service.fromNumChanged);
releasePhonePacket(); // Don't leak phone packets on shutdown releasePhonePacket(); // Don't leak phone packets on shutdown
onConnectionChanged(false); onConnectionChanged(false);