synchronized_lite 1.0.0+2 copy "synchronized_lite: ^1.0.0+2" to clipboard
synchronized_lite: ^1.0.0+2 copied to clipboard

A locking mechanism for Dart analogous to synchronized blocks in Java.

example/example.dart

import 'package:synchronized_lite/synchronized_lite.dart';

import 'dart:async';

// Using Lock as a mixin to further mimic Java-style synchronized blocks
class SomeActivity with Lock {

  bool _started = false;

  Future<bool> start() async {
    // It's correct to return a Future returned by synchronized()
    return synchronized(() async {
      if(_started)
        return false;
      // perform the start operation
      await Future.delayed(Duration(seconds: 1));
      print("Started");
      _started = true;
      return true;
    });
  }

  Future<void> stop() async {
    // It's also correct to await a synchronized() call before returning
    // It's incorrect to neither await a synchronized() call nor return its Future.
    await synchronized(() async {
      if(!_started)
        return;
      // perform the stop operation
      await Future.delayed(Duration(seconds: 1));
      print("Stopped");
      _started = false;
    });
  }
}

// Prints:
//   Started
//   Stopped
main() async {
  var a = SomeActivity();
  print("Hello");
  a.start();
  a.start();
  a.stop();
  await a.stop();
}
1
likes
40
pub points
11%
popularity

Publisher

unverified uploader

A locking mechanism for Dart analogous to synchronized blocks in Java.

Repository (GitHub)
View/report issues

License

MIT (LICENSE)

More

Packages that depend on synchronized_lite