Friday, June 21, 2024
Google search engine
HomeDevelopersEvent Loop In Dart

Event Loop In Dart

Hello programmers, If you write UI code then you should know the concepts of the Event Loop architecture of Dart. It ensures that graphics operations and events such as I/O from the disk, finger taps from the user… and so on.

If you’re looking for the best flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table of Contents….

Introduction

Did You Think ..?

Basic Concept

Some Key Points

Working on Event Loop Cycle

Code Implementation

Test Your Understanding

Conclusion

Reference


Introduction

In Computer Science, an Event Loop is a programming construct or design pattern that continually tests and manages events and calls the appropriate routine to handle them.
For example, the main function in the program is also the event loop that typically waits for the users to trigger something.


Did You Think ..?

When a program starts executing and dispose of, There are so many events that occur at that time. Can you handle these events yourself, like in which order that events execute or happen, or can you handle all of them with a single thread in that way it never blocks..?


Basic Concept

Dart

Dart is a single-threaded programming language by design because it is a single thread so everywhere we have an Asynchronous code. Many library functions return future objects and we can register handlers to respond to events such as mouse clicks, file I/O completions & timer expirations…. all kinds of stuff.

So quickly, we can say that Dart handles asynchronous programming by Event Loop.

Event Loop

  • The event loop handles the execution of multiple chunks of your program over time.
  • The event loop is what allows multiple operations in a non-blocking way
  • The multi-threaded system kernel helps handle multiple operations executing in the background
  • If there is a piece of code that may delay the response, we can tell the event loop to keep it aside until the response is received.
  • When one of these operations completes, the kernel tells the event loop so that the appropriate callback may be queued to eventually be executed

Simply, An event loop’s job is to take an item from the event queue and handle it, repeating these two steps for as long as the queue has items.


Some Key Points….

Let’s know some points before to know how the Event loop works.

Event Handling Code

Dart uses asynchronous code to handle drawing events, mouse clicks, file I/O completions, timers, and so on. This code is called the Event Handling Code.

Dart’s Event Queues

A Dart app has two queues to run the Event Loop

  • > Event Queue

The event queue contains all outside events: I/O, mouse events, drawing events, timers, messages between Dart isolates, and so on.

The event queue contains events both from Dart and from elsewhere in the system.

  • > Microtask Queue

The microtask queue is necessary because the event-handling code sometimes needs to complete a task later, before returning control to the event loop.

Is used to store some very short asynchronous internal actions. All of the actions in the Microtask Queue will be executed before the Event Queue turn


Working on Event Loop Cycle

Let’s know In which order the Event loop works step by step…

Flow Chart Diagram of Working of Event Loop

As the above flow chart shows

  • When we start App, 1st main() function execute
  • The Event loop starts its work
  • Event Loop has two queues: Microtask Queue and Event Queue.
  • First, it checks the Microtask queue and executes any microtasks, in FIFO order if any exist
  • Then it dequeues and switches to Event Queue to handle the first item of the event in FIFO order if any exist
  • Event Loop repeats the cycle: execute all microtasks and then handle the next item on the event queue in FIFO order until both queues are empty and no more events are expected
  • The event loop closed and App dispose

Code Implementation

Let’s write a sample code to understand the event loop in a practical way

Sample Code:-

Output:-

Did it confuse you?

Let me explain it step by step.

  • So let’s press the Debug button to run the main() function. The event loop initializes and executes line no. 3 & 4. The next coming event is Future so Event Loop put it somewhere later in a queue and jump to line no. 26.
  • Here’s something interesting. The next event is the Future.microstack(). It’s a microstack event so Event Loop assigns it to the microstack queue and jumps to the next event. Event loop executed lines no. 29 & 30. So until now, we have A & H printed on the screen.
  • Next Event Loop checked the microstack queue and executed microtasks in FIFO order so now we get lines no. 26 & 27 output on the screen. Event Loop dequeues the microstack queue and jumps to the event queue where it put Future() in the past.
  • Now Event loop repeats the same process to handle events. Start execution on line no. 5 . Print lines no. 7, 8, and 11. The next event is Future() so put it somewhere in a queue to print later. Now Event loop gets again a Future.microstack() so it assigns that to the microstack queue and jumps to the next event.
  • So now we also have B & F printed on the screen. Event Loop checks the microstack queue and executes microtasks in FIFO order until the microtask queue is empty. Event Loop dequeues the microstack queue then checks the Event queue and handles 1st event in the queue until a queue is empty. There are no more events expected so the app dispose

Output:-

Now you have a detailed view of the output. You can see How the Event loop handles the events and in which order it executed the event.


Test Your Understanding

Until that, you explore Event Loop, Keep in mind that

We always can’t depend on Event Loop implementation to manage and handle task orders for the event queue. The implementation might change, and Future’s then() and whenComplete() methods are better alternatives.

Schedule A Task

So when we need to manage task orders or execute some code later then we can use the following APIs provided by the dart: async library: to schedule a task.

  1. The Future class, adds an item to the end of the event queue.
  2. The top-level scheduleMicrotask() function, adds an item to the end of the microtask queue.

Let’s know first that the main() function executes synchronously all existing calls, start to finish

The above flowchart shows in which order the main() function calls the task to execute.

Note:- Use Future().then() or Future().whenComplete() method to the specific task order.

Let’s take another example to test your understanding.

sample code

Output

The output shows, how main() executes the task according to priority and how you schedule tasks according to your requirements.


Conclusion

In this article, we get a details overview of Event Loop, how it manages and deals with the Microtask queue and Event queue, and how to schedule tasks according to our requirements.

When we write asynchronous code, we might need these resources:

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

Reference:

The Event Loop and Dart
Asynchronous code is everywhere in Dart. Many library functions return Future objects, and you can register handlers to…dart.cn


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


https://flutterdevs.com/hire-developers
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments