What you are going to learn: How to run background tasks in dart or What is Isolate? How to implement new Isolate ? How get messages from new isolate? How to pass by directional messages between them?
Dart is single threaded language, but it support to run Async/Background/long-running task using Isolates. Dart allow to create/run multiple isolates in single app.
To read other articles on Async coding: click here link
What is Isolate?
Definition: An isolate is what all Dart code runs in.
Let’s breakdown it definition into parts, What Isolate is???
1- Use to implement concurrent programming.
2- Has it’s own private chunk of memory.
3- Each has separate event-loop that runs all the time and catch events(on touch, make network call, data come from network, etc) and process them.
4- Independent worker that is similar to thread but don’t share memory
5- Communicates only via messages with other isolates.
How to implement new Isolate ?
To create new isolate using “spawn” method of “Isolate” class, at least two parameters are required :
1- Method name which have code of new Isolate
Isolate.spawn(runSomethingOnNewIsolate, ........);
2- An object which can be of any type(String, int or Custom class etc)
Isolate.spawn(..............., 'first long task');
Note: Just after creating new Isolate control of this main Isolate, start executing next instructions below the new Isolate creation line, where as new Isolate keep working in parallel of main/other Isolates
To kill any isolate call its method “kill”:
isolate.kill(priority: Isolate.immediate);
Here is complete code of new isolate implementation:
How get messages from new Isolate ?
To get messages from newly created Isolate use “ReceivePort” class. Two main things in this class:
1- “receivePort.sendPort” is used to send message
2- “receivePort.listen((dynamic receivedData) {});” use to receive messages which sent by “sendPort”
Note: “listen” and “sendPort” must be of same “receivePort” object.
Here is complete code of get messages from new isolate:
How to pass by directional messages between the Isolates ?
There are two ways to pass message between the isolates: i- Using “ReceivePort” almost same way as we learn to receive messages from newly created isolate. ii- Using “stream_channel” dependency developed by dart team(Simple to use).
i- Using “ReceivePort”:
Same as previous one, only pass “ReceivePort” from both of isolates to each other:
Here is its complete code:
ii- Using “stream_channel” dependency (Recommended):
1- Add stream_channel dependency in pubspec.yaml file
dependencies:
stream_channel: ^2.0.0
2- Set receivePort object to IsolateChannel.connectReceive() and set sendPort of same receivePort object to IsolateChannel.connectSend().
3- To send messages between them use “channel.sink.add(‘message’)” and use channel.stream.listen((dynamic receivedData) {}); to receive message.