<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hayk Vardanyan on Medium]]></title>
        <description><![CDATA[Stories by Hayk Vardanyan on Medium]]></description>
        <link>https://medium.com/@haykvardanyan?source=rss-d5f729943741------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ITQVxihWlcZQP_fS</url>
            <title>Stories by Hayk Vardanyan on Medium</title>
            <link>https://medium.com/@haykvardanyan?source=rss-d5f729943741------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 02:57:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@haykvardanyan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Streams and Futures in Dart]]></title>
            <link>https://medium.com/@haykvardanyan/streams-and-futures-in-dart-e8be53f9a93e?source=rss-d5f729943741------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8be53f9a93e</guid>
            <dc:creator><![CDATA[Hayk Vardanyan]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 12:57:11 GMT</pubDate>
            <atom:updated>2023-06-28T09:11:28.812Z</atom:updated>
            <content:encoded><![CDATA[<p>Firstly, I would like to mention that <strong>Dart</strong> is a single-threaded language, executing one task at a time. You might wonder about <strong>Futures</strong> and <strong>Streams</strong>, which make the code somehow ‘<strong><em>asynchronous</em></strong>.’ However, this means that the code you write may not be executed exactly line by line as you wrote it (for example, the code in line 1 may be executed after the code in line 3). The execution sequence of the code may vary depending on how <strong>Dart</strong> handles it.</p><p>To understand how <strong>Dart</strong> manages the sequence of code execution and decides which action to perform at any given moment, we need to know about the <strong>Event Loop</strong>. You can think of it as an abstract mechanism through which the language handles asynchronous code. If you come from languages like JS or Python, you can relate it to the <strong>Event Loop</strong>s they have.</p><h3>Event Loop</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*63SEyQRmF6newufwUHv83g.png" /><figcaption><strong>The image shows how Event Loop works</strong></figcaption></figure><p>As we can see from the image above the Event Loop has two queues named “<strong>MicroTask</strong>” and “<strong>Event</strong>”, which are initialized everytime the thread is created. So there are some set of rules, according to which the Dart will execute the task in each queue. At first you must know that the <strong><em>MicroTask</em></strong> Queue has a higher priority over <strong><em>Event</em></strong> Queue and the tasks in <strong>Event</strong> Queue will not be executed until <strong><em>MicroTask</em></strong> Queue is empty. To understand it better you can consider it as a function like this:</p><pre>void eventLoop(){<br>  while (microTaskQueue.isNotEmpty){<br>      fetchFirstMicroTaskFromQueue();<br>      executeThisMicroTask();<br>      return;<br>  }<br><br>  if (eventQueue.isNotEmpty){<br>      fetchFirstEventFromQueue();<br>      executeThisEventRelatedCode();<br>  }<br>}</pre><h3>MicroTask Queue</h3><p>Consider you have some code that needs to be executed asynchronously but before giving the control to <strong>Event Loop</strong>. So you want to say to <strong>Dart</strong> that you have some code that must be executed in the future but execution of which is much more important and must be done before any task in <strong>Event Queue</strong>. Here is where the <strong>microtasks</strong> come in handy. You can create it in two ways, first one via <strong>Future</strong> named constructor Future.microtask() and the second way is to call the function scheduleMicrotask()(to be clear the Future.microtask() does nothing magical and just calls the scheduleMicrotask() behind the scenes). Here is the the code snippet of how to use it:</p><pre>import &#39;dart:async&#39;;<br><br>void main() {<br>    print(&#39;Begin&#39;);<br>    scheduleMicrotask(() =&gt; print(&#39;First microtask&#39;));<br>    Future.microtask(() {<br>      print(&#39;second microtask&#39;);<br>    });  <br>  <br>    Future(() =&gt; print(&#39;Future 1&#39;));<br> <br>    scheduleMicrotask(() =&gt; print(&#39;third microtask&#39;));<br> <br>    print(&#39;End&#39;);<br>}<br>// expexted output<br>// Begin<br>// End<br>// First microtask<br>// second microtask<br>// third microtask<br>// Future 1</pre><h3><strong>Event Queue</strong></h3><p>There are several events in case of which the latter will be handled by <strong>Event Queue</strong>, such as I/O, gesture, drawing, timers, streams and futures. In this article we are gonna talk about futures. <strong>Future</strong> represent some action that will be executed after some time in the future. When you are creating a future it is pushed to <strong>Event Queue </strong>and waits for its execution. If you want to do some action after the future will be completed you can call then() or catchError() function on that future and the corresponding function will be called directly after future execution. Here is some code to demonstrate the aforementioned:</p><pre>import &#39;dart:async&#39;;<br><br>Future&lt;void&gt; completeWithError() {<br>  return throw Exception(&quot;Exception&quot;);<br>}<br><br>Future&lt;void&gt; completeWithSuccess() {<br>  return Future.delayed(const Duration(seconds: 1));<br>}<br><br>void main() {<br>   completeWithSuccess().then((_) =&gt; (print(&#39;completed successfully&#39;)));<br>   completeWithError() <br>    .catchError((error) =&gt; print(&#39;completed with error&#39;));<br>}</pre><p>It is important to understand that both queues work in FIFO principle meaning that the event pushed firstly will be executed first.</p><h3><strong>Async/Await</strong></h3><p>Before diving into some difficult terms let’s clarify some things, the <strong>Async/Await </strong>keywords do not contradict the things said above and do not add any magic from their own, all it does is saving some boilerplate code and giving handy way to use <strong>Futures</strong>. In fact you can do all the things to achieve that performance(which <strong>await</strong> gives) without actually using them. For better understanding you can consider that <strong>Dart </strong>converts<strong> </strong>the<strong> </strong>code<strong> </strong>with<strong> async/await</strong> to simple <strong>Futures</strong> with then() function. Don’t worry if it sounded a little bit complicated I’m gonna demonstrate it with code and everything will be clear. Consider the following code</p><pre>import &#39;dart:async&#39;;<br><br>void main() async {<br>  print(&#39;start&#39;);<br>  await Future(() {<br>    print(&#39;complete the future&#39;);<br>  });<br>  print(&#39;end&#39;);<br>}</pre><p>As the keyword name suggests it is going to “wait” until the future completes and after that it will go to the next action. That means the <strong><em>print(‘end’) </em></strong>action<strong><em> </em></strong>will be executed only when the Future will be completed. But as I said we can do that without using it. Here is the code that possibly will be generated by <strong>Dart </strong>to achieve that performance:</p><pre>import &#39;dart:async&#39;;<br><br>void main() {<br>  print(&#39;start&#39;);<br>  Future(() {<br>    print(&#39;complete the future&#39;);<br>  }).then((_) {<br>    print(&#39;end&#39;);<br>  });<br>}</pre><p>For the last example I would like to show you a code that will surprise you a little bit.</p><pre>void method1(){<br>  List&lt;String&gt; myArray = &lt;String&gt;[&#39;a&#39;,&#39;b&#39;,&#39;c&#39;];<br>  print(&#39;before loop&#39;);<br>  myArray.forEach((String value) async {<br>    await delayedPrint(value);<br>  });  <br>  print(&#39;end of loop&#39;);<br>}<br><br>void method2() async {<br>  List&lt;String&gt; myArray = &lt;String&gt;[&#39;a&#39;,&#39;b&#39;,&#39;c&#39;];<br>  print(&#39;before loop&#39;);<br>  for(int i=0; i&lt;myArray.length; i++) {<br>    await delayedPrint(myArray[i]);<br>  }<br>  print(&#39;end of loop&#39;);<br>}<br><br>Future&lt;void&gt; delayedPrint(String value) async {<br>  await Future.delayed(Duration(seconds: 1));<br>  print(&#39;delayedPrint: $value&#39;);<br>}</pre><p>The outcome of this two functions is different, but why? They have the same logic and in both functions we used <strong>await </strong>keyword so in both methods the <strong><em>print(‘end of loop’); </em></strong>operation must be executed in the end. But there is one nuance that you may miss if you don’t look carefully. In <strong>method1() </strong>we are calling the method of List <strong>forEach</strong> that is written for us already(provided by Dart), all it does is to iterate over the array and calling the method we are passing through argument. Well the thing is that <strong>async</strong> is declared the function that we pass as an argument(callback function) but the function <strong>forEach </strong>itself<strong> </strong>isn’t <strong>async. </strong>The solution here would be to add <strong>await</strong> keyword in front of the call <strong>forEach, </strong>but<strong> </strong>as<strong> </strong>the<strong> forEach </strong>isn’t <strong>async</strong> the compiler will not let us do that. In case of <strong>method2() </strong>we don’t have that problem because there is no any function call we are just iterating over the array manually.</p><h3><strong>Streams</strong></h3><p>In <strong>Dart</strong>, streams play a crucial role in handling asynchronous data, making it easier to process continuous events or data streams. Whether you’re working with user input, server responses, or any other form of real-time data, streams provide a powerful mechanism for efficiently managing and reacting to such data. In this article, we will explore the concept of streams in <strong>Dart</strong>, and how create and use them. There are two kinds of streams.</p><h3>Single subscription streams</h3><p>You can have only one listener to such a stream. Listening it second time will give you an exception. Single-subscription streams have a well-defined life cycle: they start when a user starts listening, and they end when the user cancels or when the stream sends a close event.</p><h3>Broadcast streams</h3><p>You can start listening to such a stream at any time, and you get the events that are fired while you listen. More than one listener can listen at the same time, and you can listen again later after canceling a previous subscription.</p><h3><strong>Creating streams and working with them</strong></h3><p>As we already have some understandings about streams, let’s talk about how we can create and use them.</p><p>The simplest way to create a stream is to call the named constructor of Stream fromIterable():</p><pre>Stream&lt;int&gt; stream = Stream&lt;int&gt;.fromIterable([ 1, 2, 3, 4]);</pre><p>Another way is to simply mark function <strong><em>async* </em></strong>and use <strong><em>yield </em></strong>keyword to generate data for stream. Here is the generator function that returns the stream of integers:</p><pre>Stream&lt;int&gt; countStream(int to) async* {<br>  for (int i = 1; i &lt;= to; i++) {<br>    yield i;<br>  }<br>}</pre><p>You can also use <strong>StreamController </strong>to work with <strong>streams. StreamController</strong> serves as a mechanism for controlling a Stream. It provides a new stream and facilitates the addition of events to the stream from anywhere and at any time. The <strong>stream</strong> itself contains the necessary logic for managing listeners and pausing. Within each <strong>StreamController</strong>, there are two objects: the sink (used for pushing events onto the stream) and the stream (used for receiving events from the sink). Here is the code which shows how to use it:</p><pre>import &#39;dart:async&#39;;<br>void main() async {<br>  // create a StreamController<br>  final streamController = StreamController();<br>// listen to events<br>  streamController.stream.listen(print);<br>  <br>  // push events<br>  streamController.sink.add(&#39;Flutter is the Best&#39;);<br>  streamController.sink.add(100);<br>  <br>  // When you no longer need to use the controller, you can close it by using close()<br>  await Future.delayed(Duration(seconds: 2));<br>  await streamController.close();<br>}</pre><p>You created the stream now you need to listen to it. To do that you can either call <strong>listen() </strong>method on stream instance or use <strong>await for</strong> loop. <strong>listen()</strong> sets up code that will be put on the event queue when an event arrives, then following code is executed, <strong>await for</strong> suspends between events and keeps doing so until the stream is done, so code following it will not be executed until that happens. Here is the code demonstration of that:</p><pre>Stream&lt;int&gt; stream = Stream&lt;int&gt;.fromIterable([ 1, 2, 3, 4]);</pre><p>then:</p><pre>print(&#39;BEFORE&#39;);<br>stream.listen((s) { print(s); });<br>print(&#39;AFTER&#39;);</pre><p>yields:</p><pre>BEFORE<br>AFTER<br>1<br>2<br>3<br>4</pre><p>whereas:</p><pre>print(&#39;BEFORE&#39;);<br>await for(int s in stream) { print(s); }<br>print(&#39;AFTER&#39;);</pre><p>yields:</p><pre>BEFORE<br>1<br>2<br>3<br>4<br>AFTER</pre><p>It is also important to note that the generator function will only be called and start to “<strong><em>yield</em></strong>” data whenever there is a “<strong><em>someone</em></strong>” who listening to it. As for B<strong>roadcast Streams </strong>you can call asBroadcastStream() on stream instance and StreamController.broadcast() in order to get <strong>Broadcast Stream</strong>.</p><pre>final myStream = Stream&lt;int&gt;.fromIterable([ 1, 2, 3, 4]).asBroadcastStream();<br>final myControllerStream = StreamController.broadcast();<br><br>final subscription = myStream.listen(<br>  (data) =&gt; print(&#39;Data: $data&#39;),<br>);<br><br>final subscription2 = myStream.listen(<br>  (data) =&gt; print(&#39;Data again: $data&#39;),<br>);</pre><p>As an additional information the <strong>Stream</strong> class contains a number of helper methods that can do common operations on a stream for you, similar to the methods on an <strong>Iterable.</strong> For example, you can find the first positive integer in a stream using firstWhere() from the Stream API:</p><pre>Future&lt;int&gt; lastPositive(Stream&lt;int&gt; stream) =&gt;<br>    stream.firstWhere((x) =&gt; x &gt;= 0);</pre><h3><strong>Conclusion</strong></h3><p>Thank you folks for reading my article, hope I helped you to understand this topic in Dart!</p><blockquote>My LinkedIn page — <a href="https://www.linkedin.com/in/hayk-vardanyan-46996a25b/">https://www.linkedin.com/in/hayk-vardanyan-46996a25b/</a></blockquote><blockquote>My GitHub page — <a href="https://github.com/Hayk-Vardanyan">https://github.com/Hayk-Vardanyan</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8be53f9a93e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>