DISCOVER FLUTTER — WEEK #16
Reading articles on this topic, I came up with the idea to single out only the core facts concerning Isolates and the Event loop as the basis of asynchronous programming in Dart.
First and foremost Dart is single thread. When we say single thread we mean the fact that Dart executes one operation at a time, so it cannot be interrupted by any other Dart code.
Isolates
When you start your Flutter app, a new thread process is created and launched. In Dart language, this thread process is called Isolate.
I would single out the next core facts about Dart Isolates:
- Isolates = Thread process
- 1 Isolate has 1 Event Loop and 2 Queues (MicroTask and Event)— Each Isolate has its own "Event Loop" — code that runs inside an Isolate will run independently of another Isolate. So Isolates are isolated from one another.
- Isolates do not share memory, communication between different is made via messages. The receiving isolate processes the message using its Event Loop.
- Many Dart apps run all their code in a single Isolate, but you can have more than one if you need it.
Event Loop
As we mentioned above, each Isolate has its own Event Loop. The event loop is like a wheel that does not stop spinning, some kind of infinite loop. This loop launches when the Isolate is created.
I would single out the next core facts about Dart Event Loops:
- EL is created when the Isolate is created
- EL is an infinite loop
- It manages the way your code will be executed, considering the content of both 2 Queues — MicroTask and Event. The MicroTask takes precedence over the Event Queue, so when there is no longer any micro task to run, the EL will execute the first item from the Event Queue.
Note: MicroTask Queue is used for short internal actions, that need to be run asynchronously, e.g. dispose method.
Note: Event Queue is used to store all events triggered externally (gesture, drawing, timers, streams) and for Futures.
Conclusion
If you're a fan of short, interesting articles covering various Flutter topics and you want to get into the habit of learning Flutter with me over the next 13 weeks, you can read my articles every Tuesday.
If you have any questions or comments about this article, let me know in the comments section.
For those who want to jump into our Flutter journey, links from the previous weeks can be found below:
- Week #12 — "Arrange Buttons in a Row With ToggleButtons Widget"
- Week #13 — "The Stateful Widget Lifecycle"
- Week #14 — "My December Recommendations for Flutter Packages"
- Week #15 — "Reactive Programming in Flutter"
See you next week. Don't break the streak!