forked from snakster/cpp.react
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObserverBase.h
More file actions
79 lines (61 loc) · 2.01 KB
/
ObserverBase.h
File metadata and controls
79 lines (61 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Copyright Sebastian Jeckel 2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef REACT_DETAIL_OBSERVERBASE_H_INCLUDED
#define REACT_DETAIL_OBSERVERBASE_H_INCLUDED
#pragma once
#include "react/detail/Defs.h"
#include <memory>
#include <vector>
#include <utility>
#include "IReactiveNode.h"
/***************************************/ REACT_IMPL_BEGIN /**************************************/
///////////////////////////////////////////////////////////////////////////////////////////////////
/// IObserver
///////////////////////////////////////////////////////////////////////////////////////////////////
class IObserver
{
public:
virtual ~IObserver() {}
virtual void UnregisterSelf() = 0;
private:
virtual void detachObserver() = 0;
template <typename D>
friend class Observable;
};
///////////////////////////////////////////////////////////////////////////////////////////////////
/// Observable
///////////////////////////////////////////////////////////////////////////////////////////////////
template <typename D>
class Observable
{
public:
Observable() = default;
~Observable()
{
for (const auto& p : observers_)
if (p != nullptr)
p->detachObserver();
}
void RegisterObserver(std::unique_ptr<IObserver>&& obsPtr)
{
observers_.push_back(std::move(obsPtr));
}
void UnregisterObserver(IObserver* rawObsPtr)
{
for (auto it = observers_.begin(); it != observers_.end(); ++it)
{
if (it->get() == rawObsPtr)
{
it->get()->detachObserver();
observers_.erase(it);
break;
}
}
}
private:
std::vector<std::unique_ptr<IObserver>> observers_;
};
/****************************************/ REACT_IMPL_END /***************************************/
#endif // REACT_DETAIL_OBSERVERBASE_H_INCLUDED