-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_concurrency.mvvm.dart
More file actions
101 lines (93 loc) · 2.64 KB
/
02_concurrency.mvvm.dart
File metadata and controls
101 lines (93 loc) · 2.64 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import 'package:flowr/flowr_mvvm.dart';
import 'package:flutter/material.dart';
class ConcurrencyVM extends FrViewModel<int> {
@override
int get initValue => 0;
ConcurrencyVM();
// 1. Mutex (Exhaust)
// Clicking multiple times during execution will ignore subsequent calls.
Future<void> addWithMutex() async {
await update(
(old) async {
logger('Mutex: start');
await Future.delayed(const Duration(seconds: 1));
logger('Mutex: end');
return old + 1;
},
mutexTag: 'add',
);
}
// 2. Debounce
// Only the last call after 500ms of inactivity will execute.
void addWithDebounce() {
update(
(old) {
logger('Debounce: execute');
return old + 1;
},
debounceTag: 'add',
slowlyMs: 500,
);
}
// 3. Throttle
// Executed at most once every 500ms.
void addWithThrottle() {
update(
(old) {
logger('Throttle: execute');
return old + 1;
},
throttleTag: 'add',
slowlyMs: 500,
);
}
}
class ConcurrencyView extends StatelessWidget {
const ConcurrencyView({super.key});
@override
Widget build(BuildContext context) {
return FrProvider(
(c) => ConcurrencyVM(),
child: Builder(
builder: (context) {
final vm = context.read<ConcurrencyVM>();
return Scaffold(
appBar: AppBar(title: const Text('FlowR Concurrency Demo')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
StreamBuilder<int>(
stream: vm.stream,
builder: (context, snapshot) {
return Text(
'Count: ${snapshot.data}',
style: Theme.of(context).textTheme.headlineLarge,
);
},
),
const SizedBox(height: 40),
ElevatedButton(
onPressed: () => vm.addWithMutex(),
child: const Text('Add with Mutex (1s lock)'),
),
ElevatedButton(
onPressed: () => vm.addWithDebounce(),
child: const Text('Add with Debounce (500ms)'),
),
ElevatedButton(
onPressed: () => vm.addWithThrottle(),
child: const Text('Add with Throttle (500ms)'),
),
],
),
),
);
},
),
);
}
}
void main() {
runApp(const MaterialApp(home: ConcurrencyView()));
}