/
saga_monitor_example.dart
81 lines (64 loc) · 1.76 KB
/
saga_monitor_example.dart
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
import 'package:redux/redux.dart';
import 'package:redux_saga/redux_saga.dart';
import 'package:saga_monitor/saga_monitor.dart';
// Reducer method
// Changes state according to the actions dispatched
int counterReducer(int state, dynamic action) {
if (action is IncrementAction) {
return state + 1;
} else if (action is DecrementAction) {
return state - 1;
}
return state;
}
//Actions
class IncrementAction {}
class DecrementAction {}
class IncrementAsyncAction {}
//incrementAsync Saga increasing count delayed
Iterable incrementAsync({dynamic action}) sync* {
yield Delay(Duration(seconds: 1));
yield Put(IncrementAction());
}
// counterSaga takes every IncrementAsyncAction
// action and forks incrementAsync
Iterable counterSaga() sync* {
yield TakeEvery(incrementAsync, pattern: IncrementAsyncAction);
}
void main() {
// create middleware
var sagaMiddleware = createSagaMiddleware(Options(
// set saga monitor
sagaMonitor: SimpleSagaMonitor(onLog: consoleMonitorLogger),
));
// create store and apply middleware
final store = Store<int>(
counterReducer,
initialState: 0,
middleware: [applyMiddleware(sagaMiddleware)],
);
// attach store
sagaMiddleware.setStore(store);
// run root saga
sagaMiddleware.run(counterSaga);
//subscribe to the store
store.onChange.listen(render);
//dispatch some sample events
store.dispatch(IncrementAction());
store.dispatch(IncrementAction());
store.dispatch(IncrementAction());
store.dispatch(DecrementAction());
store.dispatch(IncrementAsyncAction());
// Output :
// 1
// 2
// 3
// 2
// 2
// 3
}
//this method may render the ui according to the store data
//now it is just printing to the console for every change
void render(int state) {
print(state);
}