Skip to content

Commit

Permalink
Rewrite observers to use std::vector
Browse files Browse the repository at this point in the history
  • Loading branch information
Nicolas Cornu committed Nov 22, 2023
1 parent cc566d1 commit da865a3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 48 deletions.
14 changes: 7 additions & 7 deletions src/ivos/InterViews/observe.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,30 +32,30 @@
#include <InterViews/enter-scope.h>

#include <InterViews/_enter.h>
#include <vector>

class Observer;
class ObserverList;

class Observable {
public:
Observable();
Observable() = default;
virtual ~Observable();

virtual void attach(Observer*);
virtual void detach(Observer*);
virtual void notify();
private:
ObserverList* observers_;
std::vector<Observer*> observers_;
};

class Observer {
protected:
Observer();
Observer() = default;
public:
virtual ~Observer();
virtual ~Observer() = default;

virtual void update(Observable*);
virtual void disconnect(Observable*);
virtual void update(Observable*) {};
virtual void disconnect(Observable*) {};
};

#include <InterViews/_leave.h>
Expand Down
52 changes: 11 additions & 41 deletions src/ivos/observe.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,58 +30,28 @@
*/

#include <InterViews/observe.h>
#include <OS/list.h>

declarePtrList(ObserverList,Observer)
implementPtrList(ObserverList,Observer)

Observable::Observable() {
observers_ = nil;
}
#include "utils/enumerate.h"

Observable::~Observable() {
ObserverList* list = observers_;
if (list != nil) {
// in case a disconnect removes items from the ObserverList
for (long i = list->count() - 1; i >= 0; --i) {
list->item(i)->disconnect(this);
if (i > list->count()) { i = list->count(); }
// in case a disconnect removes items from the observers
for (long long i = static_cast<long long>(observers_.size()) - 1; i >= 0; --i) {
observers_[i]->disconnect(this);
if (i > observers_.size()) {
i = observers_.size();
}
}
delete list;
}
}

void Observable::attach(Observer* o) {
ObserverList* list = observers_;
if (list == nil) {
list = new ObserverList(5);
observers_ = list;
}
list->append(o);
observers_.push_back(o);
}

void Observable::detach(Observer* o) {
ObserverList* list = observers_;
if (list != nil) {
for (ListUpdater(ObserverList) i(*list); i.more(); i.next()) {
if (i.cur() == o) {
i.remove_cur();
break;
}
}
}
erase_first(observers_, o);
}

void Observable::notify() {
ObserverList* list = observers_;
if (list != nil) {
for (ListItr(ObserverList) i(*list); i.more(); i.next()) {
i.cur()->update(this);
}
for (auto& obs: observers_) {
obs->update(this);
}
}

Observer::Observer() { }
Observer::~Observer() { }
void Observer::update(Observable*) { }
void Observer::disconnect(Observable*) { }

0 comments on commit da865a3

Please sign in to comment.