-
Notifications
You must be signed in to change notification settings - Fork 3
/
example.cpp
103 lines (88 loc) · 2.55 KB
/
example.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
#include <iostream>
#ifdef HAVE_RXCPP
#include "rx-redux.hpp"
#else
#include "redux.hpp"
#endif
//=============================================================================
int main()
{
using State = int;
using Action = std::string;
// Reducer
//=========================================================================
auto reducer = [] (State state, Action action)
{
if (action == "Increment")
return state + 1;
if (action == "Decrement")
return state - 1;
return state;
};
// Middleware functions
//=========================================================================
auto log_state = [] (auto&& store, auto next, auto action)
{
if (action == "Log")
{
std::cout << "The state is " << store.get_state() << std::endl;
}
else
{
next(action);
}
};
auto cancel_if_empty = [] (auto&& store, auto next, auto action)
{
if (! action.empty())
{
next(action);
}
else
{
std::cout << "That was an empty action!" << std::endl;
}
};
auto dispatch_more = [] (auto&& store, auto next, auto action)
{
if (action == "Dispatch")
{
store.dispatch("Increment");
store.dispatch("Log");
store.dispatch("Increment");
store.dispatch("Log");
}
else
{
next(action);
}
};
// Store creation
//=========================================================================
#ifdef HAVE_RXCPP
// If we're on RxCpp, then use the 'bottomware' option to apply a delay to
// the action stream.
auto bottomware = [] (auto o) { return o.delay(std::chrono::milliseconds(100)); };
auto store = redux::create_store(reducer, bottomware);
#else
auto store = redux::create_store(reducer);
#endif
store
.apply_middleware(dispatch_more)
.apply_middleware(log_state)
.apply_middleware(cancel_if_empty);
// Subscribe, and run it!
//=========================================================================
store.subscribe([] (State state) { std::cout << state << std::endl; });
store.dispatch("Increment");
store.dispatch("Log");
store.dispatch("Increment");
store.dispatch("Log");
store.dispatch("Decrement");
store.dispatch("Log");
store.dispatch("Decrement");
store.dispatch("Log");
store.dispatch("Dispatch");
store.dispatch(std::string());
return 0;
}