Skip to content

Instantly share code, notes, and snippets.

@guid-empty
Created June 1, 2021 09:05
Show Gist options
  • Save guid-empty/f42081158853ca08a6b0c52685f4fa68 to your computer and use it in GitHub Desktop.
Save guid-empty/f42081158853ca08a6b0c52685f4fa68 to your computer and use it in GitHub Desktop.
Usage the Synchronized package and locking the async operations demo
import 'dart:async';
import 'package:synchronized/synchronized.dart';
///
/// without synchronized logout should be the same:
/// emitting 1
/// listening the step 1
/// listening the step 1
/// emitting 1
/// listening the step 1
/// listening the step 1
/// emitting 2
/// emitting 2
/// emitting 3
/// emitting 3
/// emitting 4
/// emitting 4
/// With synchronized logout should be look like this
/// emitting 1
/// listening the step 1
/// listening the step 1
/// emitting 2
/// emitting 3
/// emitting 4
/// emitting 1
/// emitting 2
/// emitting 3
/// emitting 4
///
void main() {
final sync = SyncService();
final subscription1 = sync.startUpload()
..onDone(() {
print('done');
});
final subscription2 = sync.startUpload()
..onDone(() {
print('done');
});
Future.delayed(Duration(seconds: 4), () => subscription1.cancel());
Future.delayed(Duration(seconds: 4), () => subscription2.cancel());
}
class SyncService {
final lock = Lock();
final StreamController<int> _streamController =
StreamController<int>.broadcast();
Stream<int> get onSync => _streamController.stream;
StreamSubscription<int> startUpload() {
_upload();
return onSync.listen((event) {
print('listening the step $event');
});
}
Future<void> _upload() => lock.synchronized(() async {
await Future.delayed(Duration(seconds: 2));
print('emitting 1');
_streamController.add(1);
await Future.delayed(Duration(seconds: 2));
print('emitting 2');
_streamController.add(2);
await Future.delayed(Duration(seconds: 2));
print('emitting 3');
_streamController.add(3);
await Future.delayed(Duration(seconds: 2));
print('emitting 4');
_streamController.add(4);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment