Created
May 24, 2020 08:52
-
-
Save erluxman/ff1e8e9581285cf327e95b281585fbd7 to your computer and use it in GitHub Desktop.
Synchronous in dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'dart:io'; | |
import 'package:synchronized/extension.dart'; | |
main() async { | |
var demo = Demo(); | |
await demo.runSynchronized(); | |
await demo.runNotSynchronized(); | |
} | |
class Demo { | |
Future runNotSynchronized() async { | |
stdout.writeln('not synchronized'); | |
write1234(); | |
write1234(); | |
await Future.delayed(const Duration(milliseconds: 300)); | |
stdout.writeln(); | |
} | |
Future runSynchronized() async { | |
stdout.writeln('synchronized'); | |
synchronized(() async { | |
await write1234(); | |
}); | |
synchronized(write1234); | |
await Future.delayed(const Duration(milliseconds: 300)); | |
stdout.writeln(); | |
} | |
Future write1234() async { | |
for (var value in [1, 2, 3, 4]) { | |
await Future.delayed(const Duration(milliseconds: 30)); | |
stdout.write(value); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment