From b76424db50003d1fa90388e88508c84c64689d0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20Kelemen?= <10376327+prampec@users.noreply.github.com> Date: Thu, 14 Apr 2022 00:43:06 +0200 Subject: [PATCH] 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 --- src/Observer.h | 24 ++++++++++++------------ src/gps/GPS.cpp | 4 ++-- src/mesh/PhoneAPI.cpp | 2 +- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/Observer.h b/src/Observer.h index fb024dc8..ccc7f37b 100644 --- a/src/Observer.h +++ b/src/Observer.h @@ -11,13 +11,13 @@ template class Observable; */ template class Observer { - Observable *observed = NULL; + std::list *> observed; public: virtual ~Observer(); - /// Stop watching our current obserable - void unobserve(); + /// Stop watching the obserable + void unobserve(Observable *o); /// Start watching a specified observable void observe(Observable *o); @@ -87,21 +87,21 @@ template class Observable template Observer::~Observer() { - unobserve(); + for (typename std::list *>::const_iterator iterator = observed.begin(); iterator != observed.end(); + ++iterator) { + (*iterator)->removeObserver(this); + } + observed.clear(); } -template void Observer::unobserve() +template void Observer::unobserve(Observable *o) { - if (observed) - observed->removeObserver(this); - observed = NULL; + o->removeObserver(this); + observed.remove(o); } template void Observer::observe(Observable *o) { - // We can only watch one thing at a time - assert(!observed); - - observed = o; + observed.push_back(o); o->addObserver(this); } diff --git a/src/gps/GPS.cpp b/src/gps/GPS.cpp index 8562f0eb..aa92d96c 100644 --- a/src/gps/GPS.cpp +++ b/src/gps/GPS.cpp @@ -95,8 +95,8 @@ bool GPS::setup() GPS::~GPS() { // we really should unregister our sleep observer - notifySleepObserver.unobserve(); - notifyDeepSleepObserver.unobserve(); + notifySleepObserver.unobserve(¬ifySleep); + notifyDeepSleepObserver.unobserve(¬ifyDeepSleep); } bool GPS::hasLock() { return hasValidLocation; } diff --git a/src/mesh/PhoneAPI.cpp b/src/mesh/PhoneAPI.cpp index ca794036..033ef490 100644 --- a/src/mesh/PhoneAPI.cpp +++ b/src/mesh/PhoneAPI.cpp @@ -48,7 +48,7 @@ void PhoneAPI::close() if (state != STATE_SEND_NOTHING) { state = STATE_SEND_NOTHING; - unobserve(); + unobserve(&service.fromNumChanged); releasePhonePacket(); // Don't leak phone packets on shutdown onConnectionChanged(false);