Flutter Synchronized

Flutter Synchronized:

In this tutorial, we are going to learn Flutter Synchronized to synchronize data in flutter app.

we are using the basic lock mechanism system to prevent concurrent access to asynchronous code.

The goal is to ensure for a single process that some asynchronous operations can run without conflict. But it would not solve cross-process synchronization.

 

For a single process (single isolate) accessing some resources like (database..), it can help to

  • In a single isolate process, it provides transaction on a database system that doesn’t have transaction mechanism on Database like MongoDB, file system.
  • In HTML, the application make sure some asynchronous UI operation that is not conflicting like login, transition, etc.

Flutter Syncronized  Provides The Following Features:

  • By default, the lock is not reentrant
  • Timeout support
  • Support for reentrant lock (using Zone)
  • Consistent behavior (i.e. if it is unlocked calling synchronized grab the lock)
  • Values and Errors are properly reported to the caller
  • Work on Browser, DartVM, and Flutter
  • No dependencies (other than the SDK itself)

Using Flutter Syncronized:

see the below example code fosimple usage example.

import 'package:synchronized/synchronized.dart';

main() async {
// Use this object to prevent concurrent access to data
var lock = new Lock();
...
await lock.synchronized(() async {
// Only this block can run (once) until done
...
});
}

Using  re-entrant lock in Flutter Syncronized:

Use the below example code to use the  re-entrant lock in flutter app.

var lock = new Lock(reentrant: true);
// ...
await lock.synchronized(() async {
// do some stuff
// ...

await lock.synchronized(() async {
// other stuff
}
});

In Flutter Syncronized a basic lock is not reentrant and behaves like an async executor with a pool capacity of 1 and does not use Zone. 

Use the below sample code for basic re-entrant.

var lock = Lock();
// ...
lock.synchronized(() async {
// do some stuff
// ...
});

To save or preserve the return value use the below sample code.

int value = await lock.synchronized(() {
return 1;
});

How Flutter Syncronized works:

The previous task is done until the next tasks is executed once.

In Flutter Syncronized the re-entrant locks uses zone to know in which context a block is running in order to be reentrant. It maintains a list of inner tasks to be awaited for. 

Sample example to understanding the working of Flutter Syncronized.

Future writeSlow(int value) async {
await Future.delayed(new Duration(milliseconds: 1));
stdout.write(value);
}

Future write(List values) async {
for (int value in values) {
await writeSlow(value);
}
}

Future write1234() async {
await write([1, 2, 3, 4]);
}

while doing

write1234();
write1234();

It will print the following out put.

11223344

While doing the following

lock.synchronized(write1234);
lock.synchronized(write1234);

It will give the following out put or result

12341234

Using Syncronized in Flutter App.

Follow the below procedure to use Flutter Syncronized in flutter app.

Add the dependency package:

adding the dependency package to pubspec.yaml file. use the below code to add dependency package. After adding the dependency package run the get package method to import all the required files to the app. 

dependencies:
synchronized: ^2.1.0+1

Install the package:

You can install the package from the command line using the below code with Flutter as shown.

$ pub get

Importing the Package:

After Adding the dependency package to the pubspec.yaml file , you can now import the package into the dart code by using the below code. without adding the dependency packge to the pubspec.yaml file if you import it will show package not found an error.

import 'package:synchronized/synchronized.dart';

Complete example code for Flutter Syncronized:

import 'dart:async';
import 'dart:io';
import 'package:synchronized/synchronized.dart';

Future writeSlow(int value) async {
await Future.delayed(Duration(milliseconds: 1));
stdout.write(value);
}

Future write(List values) async {
for (int value in values) {
await writeSlow(value);
}
}

Future write1234() async {
await write([1, 2, 3, 4]);
}

class Demo {
Future test1() async {
stdout.writeln("not synchronized");
//await Future.wait([write1234(), write1234()]);
// ignore: unawaited_futures
write1234();
// ignore: unawaited_futures
write1234();

await Future.delayed(Duration(milliseconds: 50));
stdout.writeln();
}

Future test2() async {
stdout.writeln("synchronized");

var lock = Lock();
// ignore: unawaited_futures
lock.synchronized(write1234);
// ignore: unawaited_futures
lock.synchronized(write1234);

await Future.delayed(Duration(milliseconds: 50));

stdout.writeln();
}

Future readme1() async {
var lock = Lock();

// ...
await lock.synchronized(() async {
// do some stuff
});
}

Future readme2() async {
var lock = Lock();
if (!lock.locked) {
await lock.synchronized(() async {
// do some stuff
});
}
}

Future readme3() async {
var lock = Lock();
int value = await lock.synchronized(() {
return 1;
});
stdout.writeln("got value: ${value}");
}
}

Future main() async {
var demo = Demo();

await demo.test1();
await demo.test2();
await demo.readme1();
await demo.readme1();
await demo.readme3();
}

Congratulations You Have Learned Using Syncronized in Flutter….!!!

If It Is Helpful Share It With Your Friends….!!!

Leave a Reply

Categories