'Flutter/Dart: How to perform Synchronization
The question says itself, here I have a list which calling write method a couple of times but it's not providing output sequentially.
void main() {
List<int> list = [1, 2, 3, 4];
write(list);
write(list);
}
write functions takes the List and print the values in the delay of 1 millisecond
write(List<int> values) async {
for (int value in values) {
await Future.delayed(new Duration(microseconds: 1));
print(value);
}
}
Output:
I/flutter (21092): 1
I/flutter (21092): 1
I/flutter (21092): 2
I/flutter (21092): 2
I/flutter (21092): 3
I/flutter (21092): 3
I/flutter (21092): 4
I/flutter (21092): 4
Expected Output:
I/flutter (21092): 1
I/flutter (21092): 2
I/flutter (21092): 3
I/flutter (21092): 4
I/flutter (21092): 1
I/flutter (21092): 2
I/flutter (21092): 3
I/flutter (21092): 4
Solution 1:[1]
To Achieve this use synchronized lib
Add this to your package's pubspec.yaml file:
dependencies:
synchronized: ^2.2.0+2
Code Snippet:
write(List<int> values) async {
var lock = Lock();
for (int value in values) {
lock.synchronized(() {
Future.delayed(new Duration(seconds: 2));
});
print(value);
}
}
Output:
I/flutter (21092): 1
I/flutter (21092): 2
I/flutter (21092): 3
I/flutter (21092): 4
I/flutter (21092): 1
I/flutter (21092): 2
I/flutter (21092): 3
I/flutter (21092): 4
Note: synchronized block will run all the list first then only allowed to enter second one.
Solution 2:[2]
Just "await" the first write function
void main() async {
List<int> list = [1, 2, 3, 4];
await write(list);
write(list);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Mark Rotteveel |
