Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Synchronous in dart
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