]> git.tdb.fi Git - libs/game.git/blob - source/game/eventobserver.h
Decorate things which constitute the public API of the library
[libs/game.git] / source / game / eventobserver.h
1 #ifndef MSP_GAME_EVENTOBSERVER_H_
2 #define MSP_GAME_EVENTOBSERVER_H_
3
4 #include <msp/core/algorithm.h>
5 #include <msp/core/noncopyable.h>
6 #include "eventbus.h"
7 #include "mspgame_api.h"
8
9 namespace Msp::Game {
10
11 class EventSourceBase;
12
13 class MSPGAME_API EventObserver: public NonCopyable
14 {
15 private:
16         EventBus &bus;
17         std::vector<EventSourceBase *> observed_sources;
18
19 public:
20         EventObserver(EventBus &);
21         ~EventObserver();
22
23         template<typename T>
24         void observe(std::function<void(const T &)> cb)
25         { bus.add_observer<T>(*this, std::move(cb)); }
26
27         template<typename T, typename S>
28         void observe(S &, std::function<void(const T &)> );
29
30         void remove_source(EventSourceBase &);
31 };
32
33 template<typename T, typename S>
34 void EventObserver::observe(S &src, std::function<void(const T &)> cb)
35 {
36         src.add_observer(*this, std::move(cb));
37         auto i = lower_bound(observed_sources, &src);
38         if(i==observed_sources.end() || *i!=&src)
39                 observed_sources.insert(i, &src);
40 }
41
42 } // namespace Msp::Game
43
44 #endif