-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpp.cpp
139 lines (98 loc) · 2.81 KB
/
rpp.cpp
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include "rpp.h"
#include <iostream>
int main() {
using namespace std;
using namespace rpp;
auto b = observable{true};
auto x = observable{0};
auto y = observable{2};
auto z = computed{[&] {
cout << "[computing z...] ";
if (b())
return x();
else
return y();
}};
auto_run([&] { cout << "auto_run 1: z == " << z() << endl; });
auto_run([&] { cout << "auto_run 2: z == " << z() << endl; });
cout << "x = 10" << endl;
x = 10;
cout << "y = 12" << endl;
y = 12;
cout << "b = false" << endl;
b = false;
cout << "x = 100" << endl;
x = 100;
cout << "y = 102" << endl;
y = 102;
cout << "b = true" << endl;
b = true;
}
auto test() {
using namespace std;
using namespace rpp;
//
// [a] <--- (b) <-
// `- (c) <-`- (d) <-
// `---------------`{autorun}
auto a = observable{1};
auto b = computed{[&] { return a(); }};
auto c = computed{[&] { return a(); }};
auto d = computed{[&] { return b() + c(); }};
autorun([&] { cout << a() + d() << endl; });
}
auto test_lazy() {
using namespace std;
using namespace rpp;
auto a = observable{1};
auto b = computed{[&] { cout << a() << endl; }};
cout << b() << endl; // cout << 1 << endl;
a = 2; // nothing
cout << b() << endl; // cout << 2 << endl;
}
auto test_unregister() {
using namespace std;
using namespace rpp;
auto a = observable{1};
auto unregister = autorun([&] { cout << a() << endl; });
a = 2; // cout << 2 << endl;
unregister();
a = 3; // nothing
}
auto test_scope() {
using namespace std;
using namespace rpp;
auto a = observable{1};
{
auto b = computed{[&] { return a(); }};
// b goes out of scope, but is not observing a
// therefore, no unregistering needs to be done
}
a = 2; // nothing
}
auto test_auto_unregister() {
using namespace std;
using namespace rpp;
auto a = observable{1};
{
auto b = computed{[&] { return a(); }};
autorun([&] { cout << b() << endl; });
a = 2; // cout << 2 << endl;
// b goes out of scope, unregisters itself
// autorun is dangling and should therefore be unregistered as well
}
a = 3; // nothing
}
auto test_auto_unregister_dangling() {
using namespace std;
using namespace rpp;
auto a = observable{1};
{
auto b = computed{[&] { return a(); }};
autorun([&] { cout << a() << b() << endl; });
a = 2; // cout << 2 << 2 << endl;
// b goes out of scope, unregisters itself
// because invoking the autorun would be undefined behavior, should we also unregister it?
}
a = 3; // nothing
}