Jitesh Mohite
Jitesh Mohite

Reputation: 34180

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

Upvotes: 3

Views: 8861

Answers (2)

user3572554
user3572554

Reputation: 231

Just "await" the first write function

void main() async {
     List<int> list = [1, 2, 3, 4];
     await write(list);
     write(list);
 }

Upvotes: 5

Jitesh Mohite
Jitesh Mohite

Reputation: 34180

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.

Upvotes: 8

Related Questions