<?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 Emankamalnasr on Medium]]></title>
        <description><![CDATA[Stories by Emankamalnasr on Medium]]></description>
        <link>https://medium.com/@emankamalnasr33?source=rss-fb03d4c32c84------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*73ijBZ6Ln9P1x4SWzIi7Zg.jpeg</url>
            <title>Stories by Emankamalnasr on Medium</title>
            <link>https://medium.com/@emankamalnasr33?source=rss-fb03d4c32c84------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:14:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emankamalnasr33/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[Coroutines In Depth ]]></title>
            <link>https://medium.com/@emankamalnasr33/coroutines-in-depth-44b600faa2c7?source=rss-fb03d4c32c84------2</link>
            <guid isPermaLink="false">https://medium.com/p/44b600faa2c7</guid>
            <dc:creator><![CDATA[Emankamalnasr]]></dc:creator>
            <pubDate>Wed, 22 Feb 2023 13:15:44 GMT</pubDate>
            <atom:updated>2023-04-19T12:51:44.573Z</atom:updated>
            <content:encoded><![CDATA[<h3>Coroutines In depth 😎</h3><p>A <em>coroutine</em> is an instance of suspendable computation. It is conceptually similar to a thread, in the sense that it takes a block of code to run that works concurrently with the rest of the code. However, a coroutine is not bound to any particular thread. It may suspend its execution in one thread and resume in another one.</p><p><strong>If you eager to grasp these topics just bring your coffee and enjoy reading ☕️🥳 :</strong><br> 🔹The idea behind coroutine.<br> 🔹 How we build coroutines and execute tasks concurrently.<br> 🔹 Underlying structure of coroutine builder.<br> 🔹 Coroutine Scope and Structured Concurrency. <br> 🔹 Cold Observable vs Hot Observable.<br> 🔹 Channel (hot).<br> 🔹 Flow (cold).</p><h3>The idea behind coroutine:</h3><blockquote>in this section, we will discuss these points 😀 <br>1- Why coroutine consider the best way to achieve asynchronous programming with ease ?!<br>2- What suspend modifier tells us ?!</blockquote><p><strong>1- Why coroutine consider the best way to achieve asynchronous programming with ease ?!</strong><br>We want to achieve asynchronous programming in <em>“direct style code“</em> not in <em>“continuation passing style“ </em>which it makes our code very easy to read and less error-prone.</p><pre>//direct style <br>suspend fun loadContributors(service: GitHubService, params: Params): List&lt;Contributor&gt;{<br>  val repos = getOranizationRepos(service,params.org)<br>  val contributors = getRepoContributions(repos,service,params.org)<br>  return contributors.aggregate()<br>}</pre><pre>//continuation passing style <br>fun loadContributors(service: GitHubService, params: Params):List&lt;Contributor&gt;{<br>  getOranizationRepos(service,params.org){ repos -&gt;<br>      getRepoContributions(repos,service,params.org){ contributors -&gt;<br>           return contributors.aggregate()<br>      }<br>  }<br>}</pre><p><strong>2- What suspend modifier tells us 🤔?!<br></strong>▪️ When we use suspending functions we don’t block the underlying thread .<br>▪️ Each suspendable function is responsible for specific computation which may takes some time to be completed so we allow to pause its execution for some time to release the thread for other tasks and when the computation it’s completed we resume it.<br>▪️ We can only call suspend functions inside suspend functions or coroutineBuilder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*_YqtHUC9Y84I46ygsFHfnw.gif" /></figure><h3>How we build coroutines and execute tasks concurrently:</h3><blockquote>in this section , we will discuss these points 😀<br>1- How to call suspend function ?!<br>2- What is coroutine builder ?!<br>3- What is the differences between runBlocking,launch,async ?!</blockquote><p><strong>1- How to call suspend function?!</strong><br>Every suspending function needs to be called by another suspending function, which is called by another suspending function, and so on. This all needs to start somewhere. It starts with a coroutine builder, a bridge from the normal to the suspending world.</p><pre>fun main() = runBlocking{<br>  launch {<br>    val result = loadData()<br>    updateResults(result)<br>  }<br>}<br><br>suspend fun loadData(): Data{<br>  delay(1000)<br>  return Data(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;)<br>}</pre><p><strong>2- What is coroutine builder ?!</strong><br>Coroutine builders are a way of creating coroutines. Since they are not suspending themselves, they can be called from non-suspending code or any other piece of code. They act as a link between the suspending and non-suspending parts of our code.</p><pre>//this will create a coroutine <br>launch{<br>  <br>}</pre><p><strong>3- What is the differences between runBlocking,launch,async ?!</strong></p><p>◾️<strong>runBlocking</strong><br>runBlocking is a coroutine builder that blocks the current thread until all tasks of the coroutine it creates, finish.<br>🖇 <em>Note : we only use it for testing</em></p><pre>fun main(){<br>  runBlocking{<br>      printWorld()<br>      println(&quot;Hello!&quot;)<br>  }<br>  println(&quot;Hello Main Thread..&quot;)<br>}<br><br>suspend fun printWorld() {<br>    delay(1000L)<br>    println(&quot;World!&quot;)<br>}</pre><pre>World!<br>Hello!<br>Hello Main Thread..</pre><p>◾️<strong>launch(fire and forget)</strong><br>▪️ launch creates a new coroutine that won’t return any result to the caller.<br>▪️ it doesn’t block the underlying thread.<br>▪️ it starts a new computation which it may takes long time but it gets suspended to release the thread for other tasks and once the computation is completed it resume the coroutine itself .<br><em>🖇 Note : Not necessarily the coroutine resumes on the same thread.</em></p><pre>fun main() {<br>    runBlocking {<br>        launch {<br>            printWorld()<br>        }<br>        println(&quot;Hello!&quot;)<br>    }<br>    println(&quot;Hello Main Thread..&quot;)<br>}<br><br>suspend fun printWorld() {<br>    delay(1000L)<br>    println(&quot;World!&quot;)<br>}</pre><pre>Hello!<br>World!<br>Hello Main Thread..</pre><p>◾️<strong>async</strong><br>async the same as launch but the only difference it returns some value to the caller (Deferred&lt;T&gt;).</p><pre>fun main() {<br>    runBlocking {<br>        val d : Deferred&lt;Int&gt; = async {<br>            println(&quot;Hello Async..&quot;)<br>            getSum()<br>        }<br>        launch {<br>            println(&quot;Sum is :${d.await()}&quot;)<br>        }<br>        println(&quot;Hello!&quot;)<br>    }<br>    println(&quot;Hello Main Thread..&quot;)<br>}<br><br>suspend fun getSum() : Int{<br>    delay(1000L)<br>    return 50<br>}</pre><pre>Hello!<br>Hello Async..<br>Sum is :50<br>Hello Main Thread..</pre><h3>Underlying structure of coroutine builder :</h3><blockquote>in this section , we will discuss these points 😀 <br>1- What is the signature of coroutine builder function ?!<br>2- What is CoroutineScope ?!<br>3- What is CoroutineContext ?!<br>4- What is CoroutineDispatcher?!</blockquote><p><strong>1- What is the signature of coroutine builder function ?!</strong><br>launch,async at the end they are extension functions to CoroutineScope where you can pass the suspended function you want as an argument .</p><pre>fun CoroutineScope.launch(<br>    context: CoroutineContext = EmptyCoroutineContext, <br>    start: CoroutineStart = CoroutineStart.DEFAULT, <br>    block: suspend CoroutineScope.() -&gt; Unit<br>): Job</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*z3bCtzmSjCjriBnAeNlPHg.png" /></figure><p><strong>2- What is Coroutine Scope?!<br></strong>▪️ When ever you create a coroutine it gets attached to a special instance of coroutine scope .<br>▪️ This coroutine scope which helps us to determine the life cycle of each coroutine we have .<br>▪️ Regardles of being a parent or a child coroutine each one has its own unique coroutine scope.</p><pre>fun main () {<br>  runBlocking { //this refers to an instance of Coroutine Scope<br>      println(&quot;$this&quot;)<br>      launch { //this refers to another instance of Coroutine Scope<br>        println(&quot;$this&quot;)<br>      }<br>      <br>      async { //this refers to another instance of Coroutine Scope <br>        println(&quot;$this&quot;)<br>      }<br>  }<br>}</pre><pre>BlockingCoroutine{Active}@1f89ab83<br>StandaloneCoroutine{Active}@64cee07<br>DeferredCoroutine{Active}@6f79caec</pre><p><strong>3- What is Coroutine Context?!<br></strong>▪️ Coroutines always execute in some context represented by a value of the CoroutineContext type.<br>▪️ Unlike coroutine scope ,coroutine context can be inherited from parent coroutine.<br>▪️ Coroutine context consists of 2 main elements [job of coroutines and its Dispatcher].</p><pre>fun main() {<br>  runBlocking{ <br>    // coroutineContext<br>    // run on the main thread <br>    // confined coroutine<br>     launch{<br>         // parent coroutineContext<br>         // run on main thread<br>         println(&quot;starts on thread: ${Thread.currentThread().name}&quot;)<br>         delay(1000)<br>         println(&quot;resumed on thread: ${Thread.currentThread().name}&quot;)<br>     }<br>  }<br>}</pre><pre>fun main() {<br>  runBlocking{ <br>    // coroutineContext<br>    // run on the main thread <br>    // confined coroutine<br>     launch(coroutineContext){<br>         // parent coroutineContext<br>         // run on main thread<br>         println(&quot;starts on thread: ${Thread.currentThread().name}&quot;)<br>         delay(1000)<br>         println(&quot;resumed on thread: ${Thread.currentThread().name}&quot;)<br>     }<br>  }<br>}</pre><pre>starts on thread: main<br>resumed on thread: main</pre><p><strong>4- What is CoroutineDispatcher?!<br></strong>▪️ The coroutine context includes a coroutine dispatcher that determines what thread or threads the corresponding coroutine uses for its execution.<br>The coroutine dispatcher can confine coroutine execution to a specific thread, dispatch it to a thread pool, or let it run unconfined.</p><pre>fun main(){<br>    runBlocking {<br>        println(&quot;parent coroutine thread: ${Thread.currentThread().name}&quot;)<br>        launch(Dispatchers.Unconfined) {<br>            println(&quot;runs initially on thread: ${Thread.currentThread().name}&quot;)<br>            delay(1000)<br>            println(&quot;resumed on different thread: ${Thread.currentThread().name}&quot;)<br>        }<br>    }<br>}</pre><pre>parent coroutine thread: main<br>runs initially on thread: main<br>resumed on different thread: kotlinx.coroutines.DefaultExecutor</pre><h3>Coroutine Scope and Structured Concurrency :</h3><blockquote>in this section , we will discuss these points 😀<br>1- What is the idea of declaring coroutine inside CoroutineScope?<br>2- What is Structured Concurrency?<br>3- What is Global Scope and its disadvantages?</blockquote><p><strong>1- What is the idea of declaring coroutine inside CoroutineScope?</strong><br>▪️ New coroutines usually need to be started inside a scope. <br>▪️ Coroutine scope is necessarily to determine the lifecycle of the coroutine.</p><p><strong>For example:</strong><br>Consider that you have a screen in your application which requests some data from server. you started a coroutine to perform this request but later on you changed your mind and left that screen , at this moment we want to cancel the coroutine we’ve started.</p><pre>class MyUIClass {<br>    val scope = MainScope()<br>    fun destroy() { <br>        scope.cancel()<br>    }<br>    fun showSomeData() = scope.launch {<br>       val data = getData()<br>       updateResults(data)<br>    }<br>}</pre><p><strong>2- What is Structured Concurrency?</strong><br>When you create a coroutine inside another coroutine we consider the outer coroutine as a parent and the nested one as a child. This “parent-child” relationship works through scopes; the child coroutine is started from the scope corresponding to the parent coroutine.The mechanism behind the structure of the coroutines is called <em>structured concurrency</em>.</p><p>The scope can automatically cancel child coroutines if something goes wrong or a user changes their mind and decides to revoke the operation.</p><pre>//we have the option to cancel the job<br>job.cancel()<br><br><br>val job = launch { //outer coroutine(parent)<br>   val contributors = loadContributors(service, params)<br>   updateResults(contributors)<br>}</pre><pre>suspend fun loadContributors(service: GitHubService, params: Params): List&lt;Contributor&gt;{<br>  val repos = getOranizationRepos(service,params.org)<br>  val deferredsContributors = getRepoContributions(repos,service,params.org)<br>  return deferredsContributors.awaitAll().flatten().aggregate()<br>}</pre><pre>suspend fun getRepoContributions(<br>    repos:List&lt;Repo&gt;,<br>    service: GitHubService,<br>    org: String<br>){<br>    val deferreds: List&lt;Deferred&lt;List&lt;Contributor&gt;&gt;&gt; = repos.map { repo -&gt;<br>        async { //nested coroutines(childs)<br>            service.getRepoContributors(params.org, repo.name)<br>                .also { logContributors(repo, it) }<br>                .body() ?: emptyList()<br>        }<br>    }<br>    return deferreds<br>}</pre><p><strong>⚠️ 3- What is Global Scope and its disadvantages?</strong><br>A global CoroutineScope not bound to any job. Global scope is used to launch top-level coroutines which are operating on the whole application lifetime.This is a delicate API. It is easy to accidentally create resource or memory leaks when global scope is used.</p><p><strong>Example:</strong><br>A call to loadConfiguration creates a coroutine in the GlobalScope that works in background without any provision to cancel it or to wait for its completion. If a network is slow, it keeps waiting in background, consuming resources. Repeated calls to loadConfiguration will consume more and more resources.</p><pre>fun loadConfiguration() {<br>    GlobalScope.launch {<br>        val config = fetchConfigFromServer()<br>        updateConfiguration(config)<br>    }<br>}</pre><p><strong>A simple solution:</strong><br>In many cases uses of GlobalScope should be removed, marking the containing operation with suspend, for example:</p><pre>suspend fun loadConfiguration() {<br>    val config = fetchConfigFromServer()<br>    updateConfiguration(config)<br>}</pre><p><strong>Bad usage of global scope:</strong><br>We launched child coroutines inside GlobalScope which is tied to application lifecycle not to parent coroutine life cycle.when you try to cancel the parent coroutine in case of some problem the child coroutines still working at background which is very bad design.</p><pre>job.cancel()<br><br>val job = launch { //outer coroutine (parent)<br>   val repos = getOranizationRepos(service,params.org)<br>   val deferreds = repos.map { repo -&gt;<br>        GlobalScope.async { //nested coroutine(child)<br>            service.getRepoContributors(params.org, repo.name)<br>                .also { logContributors(repo, it) }<br>                .body() ?: emptyList()<br>        }<br>    }<br>  updateResults(deferreds.awaitAll().flatten().aggregate())  <br>}</pre><h3>Cold Observable vs Hot Observable :</h3><blockquote>in this section we will discuss these points 😀<br>1- When to use Observer design pattern?!<br>2- What is Observable?!<br>3- What is the difference between cold observable and hot observable?!</blockquote><p><strong>1- When to use Observer design pattern?!</strong><br>Observer pattern is the recommended way to deal with many asynchronous operations that require changing the data, performing different operations on a data stream.we can see that observable emits multiple values as a sequence of data that passes over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7vgFkIMXIBbpidSSSFo4WQ.png" /></figure><p><strong>2- What is Observable?!</strong><br>Observables is a simply a collection of data that waits to be invoked (subscribed) before it can emit any data.</p><p><strong>3- What is the difference between cold observable and hot observable?<br>Cold Observable (Lazy Stream):<br></strong>▪️ Cold observables start to emit values only when we subscribe to them.<br>▪️ Cold observable are unicast .<br> <em>[which means that the observable does a new execution for every subscriber ,the produced data itself is different for each subscriber].</em><br>▪️ Data is produced inside the observable.</p><pre>val observable = Observable.create((observer) -&gt; {<br>   observer.next(Math.random())<br>})<br><br>observable.subscribe((data) -&gt; {<br>  println(data) //123<br>})<br><br>observable.subscribe((data) -&gt; {<br>  println(data) //456<br>})</pre><p><strong>Hot Observable (Eager Stream):<br></strong>▪️ Hot observables emits values always despite we have subscribers or not.<br>▪️ Hot observables are multicast .<br> <em>[which means that all subscribers have the same data].</em><br>▪️ Data is produced outside the observable.</p><pre>// we moved tha data producer outside the creation of the observable <br>val random = Math.random() //123<br><br>val observable = Observable.create((observer) -&gt; {<br>   observer.next(random)<br>})<br><br>observable.subscribe((data) -&gt; {<br>  println(data) //123<br>})<br><br>observable.subscribe((data) -&gt; {<br>  println(data) //123<br>})</pre><p><strong>When to use cold or hot observables ?</strong><br>We usually use cold observable unless you need all your subscribers to share the same data .</p><h3>Channels (hot streams):</h3><blockquote>in this section , we’ll discuss these points 😀<br>1- How to transfer single/multiple values between coroutines ?!<br>2- What is underlying structure of channel?!<br>3- What is channel producer and channel consumer?!<br>4- Why channels are considered hot?!<br>5- What are types of channel and when to use each one?!</blockquote><p><strong>1- How to transfer single/multiple values between coroutines ?!<br></strong>▪️ Deferred values provide a convenient way to transfer a single value between coroutines.<br>▪️ Channels provide a way to transfer a stream of values.</p><pre>//Deferred Way<br>fun main() = runBlocking{<br>    val d1 = async {<br>        println(&quot;coroutine 1 started&quot;)<br>        getD1()<br>    }<br>    val d2 = async {<br>        println(&quot;coroutine 2 started&quot;)<br>        getD2()<br>    }<br>    delay(3000)<br>    println(&quot;delay on main coroutine finished&quot;)<br>    println(&quot;check equality: ${d1.await() == d2.await()}&quot;)<br>}<br><br>suspend fun getD1(): Int{<br>    delay(1000)<br>    println(&quot;delay on coroutine 1 finished&quot;)<br>    return 1<br>}<br><br>suspend fun getD2(): Int{<br>    delay(2000)<br>    println(&quot;delay on coroutine 2 finished&quot;)<br>    return 2<br>}</pre><pre>coroutine 1 started<br>coroutine 2 started<br>delay on coroutine 1 finished<br>delay on coroutine 2 finished<br>delay on main coroutine finished<br>check equality: false</pre><p><strong>Channels way:</strong><br>Suppose we have 3 coroutines (One is responsible for producing data and the other two are responsible for recieving data).<br>While 2 coroutines are available they can receive data at the same time.<br>While coroutine 2 is suspended the coroutine 1 continue receiving data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z05OJ_IcuDdHak0CDHqeCw.png" /></figure><pre>fun main(){<br>    val channel = Channel&lt;Int&gt;()<br><br>    runBlocking {<br>        launch {<br>            //coroutine 2<br>            //consumer<br>            //start receiving values from channel<br>            // here we print received values until the channel is closed.<br>            for(num in channel){<br>                println(&quot;coroutine 1: num received is $num&quot;)<br>            }<br>        }<br><br>        launch {<br>            //coroutine 1<br>            //consumer<br>            //start receiving values from channel<br>            // here we print received values until the channel is closed.<br>            for(num in channel){<br>                delay(1000)<br>                println(&quot;coroutine 2: num received is $num&quot;)<br>            }<br>        }<br><br>        launch {<br>            //coroutine 3<br>            //producer<br>            //this is responsible for producing values that&#39;ll be sent to the channel<br>            listOf(1,2,3,4).forEach {<br>                channel.send(it)<br>            }<br><br>            //is like sending a special close token to the channel.<br>            //indicator that we&#39;re done sending<br>            channel.close()<br>        }<br>    }<br>}</pre><pre>coroutine 1: num received is 1<br>coroutine 1: num received is 3<br>coroutine 1: num received is 4<br>coroutine 2: num received is 2</pre><p><strong>2- What is underlying structure of channel?!<br></strong>A Channel is conceptually very similar to BlockingQueue. One key difference is that instead of a blocking put operation it has a suspending send, and instead of a blocking take operation it has a suspending receive.</p><p><strong>Why send/recieve are suspending functions 🙄?!</strong><br><em>Because this happens when channel is empty or full:</em><br>▪️ When the channel is empty we can’t receive yet so recieve will be suspended until any element is sent to the channel.<br>▪️ When the channel has limited size we can’t send if channel is full so send will be suspended until channel has a free space again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*V6gE3XAKsI2JDQeW8ZVudw.png" /></figure><p><strong>3- What is channel producer and channel consumer?!</strong><br>The pattern where a coroutine is producing a sequence of elements is quite common. This is a part of <em>producer-consumer</em> pattern that is often found in concurrent code.</p><p><strong>Channel producer </strong>💁‍♀️ : <br>Launches a new coroutine to produce a stream of values by sending them to a channel and returns a reference to the coroutine as a ReceiveChannel.</p><pre>@ExperimentalCoroutinesApi<br>fun &lt;E&gt; CoroutineScope.produce(<br>    context: CoroutineContext = EmptyCoroutineContext, <br>    capacity: Int = 0, <br>    block: suspend ProducerScope&lt;E&gt;.() -&gt; Unit<br>): ReceiveChannel&lt;E&gt;</pre><pre>fun CoroutineScope.produceSquares()<br> : ReceiveChannel&lt;Int&gt; = produce {<br>    for (x in 1..5){<br>       send(x * x)<br>    } <br>}<br><br>//it&#39;s the same if we created channel in regular way <br>fun CoroutineScope.channel(){<br>  val squareChannel = Channel&lt;Int&gt;()<br>  launch {<br>     listOf(1,2,3,4,5).forEach {<br>        squareChannel.send(it * it)<br>     }<br>     squareChannel.close()<br>  }<br><br>}</pre><p><strong>Channel consumer 🙋‍♀️:</strong><br>The resulting object that is returned by the channel producer can be used to receive elements produced by the coroutine and then performs a given action for each received element.</p><pre>inline suspend fun &lt;E&gt; ReceiveChannel&lt;E&gt;.consumeEach(action: (E) -&gt; Unit)</pre><pre>//consumer<br>  squareChannel.consumeEach {<br>     println(it) <br>  }<br><br>//regular way <br>for(item in squareChannel){<br>   println(item)<br>}</pre><p><strong>4- Why channels are considered hot streams?!</strong></p><pre>@OptIn(ExperimentalCoroutinesApi::class)<br>fun CoroutineScope.channelProducer(): ReceiveChannel&lt;Int&gt; {<br>    return produce {<br>        println(&quot;Channel started&quot;)<br>        listOf(1,2,3).forEach {<br>            delay(1000)<br>            send(it)<br>        }<br>    }<br>}<br><br>val channel = channelProducer()</pre><pre>Channel started</pre><p>▪️ The code inside channel get executed immediately but it’s suspended until the receiver is ready.<br>▪️ When also receiving from the channel ,each element can be received only once, after the first receiver consumes all the elements, the second one will find a channel that is empty and closed already.<br><em>That’s why it’s considered hot</em></p><pre>fun channelConsumer(){<br> runBlocking {<br>   val channel = channelProducer()<br>   delay(1000)<br>   <br>   println(&quot;receive from channel...&quot;)<br>   channel.consumeEach {<br>     println(it)<br>   }<br><br>   println(&quot;receive again from channel...&quot;)<br>   channel.consumeEach {<br>      println(it)<br>   }<br> }<br>}</pre><pre>Channel started<br>receive from channel...<br>1<br>2<br>3<br>receive again from channel...</pre><p><strong>5- What are types of channel?!<br></strong>Several types of channels are defined in the library (<em>Unlimited</em>,<em>Buffered</em>,<em>Rendezvous</em>,<em>Conflated</em>) <br>When you create a channel, specify its type or the buffer size (if you need a buffered one):</p><pre>val rendezvousChannel = Channel&lt;String&gt;() //default type<br>val bufferedChannel = Channel&lt;String&gt;(10)<br>val conflatedChannel = Channel&lt;String&gt;(CONFLATED)<br>val unlimitedChannel = Channel&lt;String&gt;(UNLIMITED)</pre><p><strong>For all of the channel types:</strong><br>-The receive() call behaves similarly,<br>it receives an element if the channel is not empty; otherwise, it is suspended.</p><p><strong>They differ in:</strong><br>- How many elements they can internally store.<br>- Whether the send() call can be suspended or not.</p><p><strong>Let’s go deep and understand each type 🥳 :</strong></p><ul><li><strong>Unlimited Channel</strong><br>✅ Producers can send elements to this channel and it will keep growing indefinitely. <br>✅ The send() call will never be suspended.<br>✅ If the program runs out of memory, you’ll get an OutOfMemoryException.</li><li>📎 Note: <br>The difference between an unlimited channel and a queue is that:<br>when a consumer tries to receive from an empty channel, it becomes suspended until some new elements are sent.</li><li><strong>Buffered Channel</strong><br>✅ The size of a buffered channel is constrained by the specified number.<br>✅ Producers can send elements to this channel until the size limit is reached.<br>✅ When the channel is full, the next send() call on it is suspended <br> until more free space becomes available.</li><li><strong>Conflated Channel</strong><br>✅ A new element sent to the conflated channel will overwrite the previously sent element.<br>✅ The receiver will always get only the latest element. <br>✅ The send() call is never suspended.</li><li><strong>Rendezvous Channel (default channel type)</strong><br>✅ It is a channel without a buffer, the same as a buffered channel with zero size.<br>✅ One of the functions (send() or receive()) is always suspended until the other is called.<br> If send is invoked first, then it is suspended until receive is invoked.<br> If receive is invoked first, it is suspended until send is invoked.<br>✅ The “rendezvous” name (“a meeting at an agreed time and place”) refers to the fact that<br> send() and receive() should “meet on time”.</li></ul><pre>fun main() = runBlocking&lt;Unit&gt; {<br>    val channel = Channel&lt;String&gt;()<br>    launch {<br>        channel.send(&quot;A1&quot;)<br>        //it may get suspended if there&#39;s no receiver is ready to receive it.<br>        channel.send(&quot;A2&quot;)<br>        <br>        log(&quot;A done&quot;)<br>    }<br>    launch {<br>        channel.send(&quot;B1&quot;)<br>        log(&quot;B done&quot;)<br>    }<br>    launch {<br>        repeat(3) {<br>            val x = channel.receive()<br>            log(x)<br>        }<br>    }<br>}<br><br>fun log(message: Any?) {<br>    println(&quot;[${Thread.currentThread().name}] $message&quot;)<br>}</pre><pre>[main] A1<br>[main] B1<br>[main] A done <br>[main] B done<br>[main] A2</pre><h3>Flow(cold stream):</h3><blockquote>in this section , we will discuss these points 😀<br>1- How we populate multiple values in kotlin in synchronous/Asynchronous way ?!<br>2- Why flow is considered as a cold stream?!<br>3- What is flow builder and discover its underlying structure?!<br>4- What is the difference between intermediate and terminal operators?!<br>5- What is shared flow (hot stream) ?!<br>6- What is state flow (hot stream) ?!<br>7- How to convert cold flow into shared/state flow using shareIn/stateIn operator?!</blockquote><p><strong>1- How we populate multiple values in kotlin in synchronous/Asynchronous way ?!</strong></p><p>▪️ <strong>Populate multiple values in kotlin (collections,sequence) in synchronous way:<br></strong>when calling fun A() ,it will populate every 1 sec some value <br>when calling fun B(), it waits 3 sec then populate the list.</p><pre>fun main(){<br>   A().foreach{v -&gt; println(v)}<br>   B().foreach{v -&gt; println(v)}<br>}<br><br>fun A(): Sequence&lt;Int&gt; = sequence{<br>  for(i in 1..3){<br>    Thread.sleep(1000)<br>    yield(i)<br>  }<br>}<br><br>fun B(): List&lt;Int&gt;{<br>   Thread.sleep(3000)<br>   return listOf(1,2,3)<br>}</pre><p>▪️ <strong>Populate multiple values in kotlin (collections,flow) in Asynchronous way:<br></strong>when calling A() it will get suspended because of delay , it will continue to perform other tasks like print statement and launching another coroutine.</p><pre>fun main(){<br>    runBlocking {<br>        //coroutine 1<br>        launch{<br>            A().forEach {v -&gt; println(&quot;from list: $v&quot;)}<br>        }<br>        println(&quot;while coroutine is suspended&quot;)<br>        //coroutine 2<br>        launch{<br>            B().collect{v -&gt; println(&quot;from flow: $v&quot;)}<br>        }<br>    }<br>}<br><br>suspend fun A(): List&lt;Int&gt; {<br>    delay(3000)<br>    return listOf(1, 2, 3)<br>}<br><br> fun B(): Flow&lt;Int&gt; = flow {<br>     println(&quot;Flow started&quot;)<br>     for (i in 1..3) {<br>         delay(1000)<br>         emit(i)<br>     }<br> }</pre><pre>while coroutine is suspended<br>Flow started<br>from flow: 1<br>from flow: 2<br>from list: 1<br>from list: 2<br>from list: 3<br>from flow: 3</pre><p><strong>2- Why flow is considered as a cold stream?!</strong><br>Flows are <em>cold</em> streams similar to sequences — the code inside a flow builder does not run until the flow is collected.Each terminal operation on a flow starts processing from scratch.</p><pre>fun main() = runBlocking&lt;Unit&gt; {<br>    println(&quot;Calling simple function...&quot;)<br>    val flow = simple()<br>    println(&quot;Calling collect...&quot;)<br>    flow.collect { value -&gt; println(value) } <br>    println(&quot;Calling collect again...&quot;)<br>    flow.collect { value -&gt; println(value) }<br>}<br><br>fun simple(): Flow&lt;Int&gt; = flow { //this refers to FlowCollector<br>    println(&quot;Flow started&quot;)<br>    for (i in 1..3) {<br>        delay(1000)<br>        emit(i)<br>    }<br>}</pre><pre>Calling simple function...<br>Calling collect...<br>Flow started<br>1<br>2<br>3<br>Calling collect again...<br>Flow started<br>1<br>2<br>3</pre><p><strong>3-</strong> <strong>What is flow builder and discover its underlying structure?!<br></strong>We can create the flows using the flow builder APIs and the function called flow for to create manually and emit the new values into the data stream using emit function.</p><p><strong>Let’s discover flow function signature</strong></p><pre>fun &lt;T&gt; flow(@BuilderInference block: suspend FlowCollector&lt;T&gt;.() -&gt; Unit): Flow&lt;T&gt;</pre><p>Let’s zoom in block argument type<strong>👀 <em>suspend FlowCollector&lt;T&gt;.() -&gt; Unit</em></strong> :<br>It is an extension function to FlowCollector and this tell us we can use any member of that receiver object in function body .</p><pre>val flowExample = flow { //this refers to a FlowCollector instance<br>    //we can access any member of FlowCollector,<br>    //for example: emit function <br>    listOf(1,2,3).forEach{<br>       emit(it)<br>    }<br>}</pre><pre>interface FlowCollector&lt;in T&gt; {<br>   suspend fun emit(value: T): Unit<br>}</pre><p><strong>Let’s discover collect function signature</strong></p><pre>interface Flow&lt;out T&gt; {<br>   suspend fun collect(collector: FlowCollector&lt;T&gt;): Unit<br>}</pre><p>Let’s zoom in collector argument type<strong>👀 <em>collector: FlowCollector&lt;T&gt;</em></strong> :<br>It is an object of type FlowCollector&lt;T&gt; , so we can create anonymous object that will override emit function.</p><pre>val collector = object : FlowCollector&lt;Int&gt; {<br> override suspend fun emit(value: Int){<br>   println(value)<br> }<br>}</pre><p>Because it’s only one function so we easily can convert it as a lambda and whenever we call collect we execute the body of emit function</p><pre>flowExample.collect{ value -&gt; println(value) }</pre><p><strong>4- What is the difference between intermediate and terminal operators?</strong></p><p><strong>Intermediate operators :</strong><br>▪️ Flows can be transformed using operators, in the same way as you would transform collections and sequences.<br>▪️ These operators are cold, just like flows are.<br>▪️ A call to such an operator is not a suspending function itself. It works quickly, returning the definition of a new transformed flow.</p><p><strong>Terminal operators:</strong><br>▪️ Terminal operators on flows are suspending functions that start a collection of the flow. The collect operator is the most basic one.</p><pre>suspend fun performRequest(request: Int): String {<br>    delay(1000)<br>    return &quot;response $request&quot;<br>}<br><br>fun main() = runBlocking {<br>    val flowEample = flow{<br>        listOf(1,2,3).forEach {<br>            emit(it)<br>        }<br>    }<br><br>    val transformedFlow = flowEample.map {<br>        performRequest(it)<br>    }<br><br>    transformedFlow.collect{<br>        println(it)<br>    }<br>}</pre><p><strong>5- What is shared flow (hot stream) ?!<br></strong>▪️ A shared<em> </em>flow that shares emitted values among all its collectors in a broadcast fashion (publisher → producer , subscribers → consumers).<br>▪️ A shared flow is called hot because its active instance exists independently of the presence of collectors.This is opposed to a cold flow which is started separately for each collector.<br>▪️ There are cases in which we want multiple receivers to be subscribed to one source of changes.<br>▪️ Shared Flow is useful for broadcasting events that happen inside an application to subscribers that can come and go.</p><p><strong>In Example below :</strong><br>- Numbers flow has started to emit values before any subscriber has exist .<br>- Subscriber A has started to collect after 2 second so it losted first emitted value .<br>- Subscriber B has started to collect after 3 seconds so it losted first two emitted values.</p><pre>fun main(){<br>    sharedFlow()<br>}<br><br>fun sharedFlow(){<br> runBlocking {<br>    val numbers = MutableSharedFlow&lt;Int&gt;()<br>    launch {<br>        repeat(3) {<br>            delay(1000)<br>            println(&quot;emit $it&quot;)<br>            numbers.emit(it)<br>        }<br>    }<br>    delay(2000)<br>    launch {<br>        numbers.collect {<br>            println(&quot;subscriber A: $it collected&quot;)<br>        }<br>    }<br>    delay(1000)<br>    launch {<br>        numbers.collect {<br>            println(&quot;subscriber B: $it collected&quot;)<br>        }<br>    }<br>    launch {<br>        numbers.collect {<br>            println(&quot;subscriber C: $it collected&quot;)<br>        }<br>    }<br> }<br>}</pre><pre>emit 0<br>emit 1<br>subscriber A: 1 collected<br>emit 2<br>subscriber A: 2 collected<br>subscriber B: 2 collected<br>subscriber C: 2 collected</pre><p><strong>6 — What is State Flow (hot stream)?!<br></strong>▪️ A State Flow that represents a read-only state with a single updatable data value that emits updates to the value to its collectors.<br>▪️ A State Flow is a<em> </em>hot<em> </em>flow because its active instance exists independently of the presence of collectors.<br>▪️ Its current value can be retrieved via the value property.<br>▪️ StateFlow is useful as a data-model class to represent any kind of state.</p><pre>class StateModel {<br>    private val _state = MutableStateFlow(initial)<br>    // read-only public view<br>    val state = _state.asStateFlow() <br><br>    fun update(newValue: Value) {<br>        _state.value = newValue<br>    }<br>}</pre><p><strong>Example:</strong><br>when we launch the coroutine 1 and gets suspended the state is changed to C so when we resume the coroutine again it concerned only with the latest updated value.</p><pre>fun main(){<br>    stateFlow()<br>}<br><br>fun stateFlow(){<br>    runBlocking {<br>        val state = MutableStateFlow(&quot;A&quot;)<br>        println(state.value)<br><br>        state.value = &quot;B&quot;<br>        launch {<br>            //coroutine 1<br>            state.collect { println(&quot;Value changed to $it&quot;) }<br>        }<br>        state.value = &quot;C&quot;<br>        delay(1000)<br><br>        state.value = &quot;D&quot;<br>        delay(1000)<br>        launch {<br>            state.collect { println(&quot;Value changed again to $it&quot;) }<br>        }<br><br>        println(&quot;done&quot;)<br>    }<br>}</pre><pre>A<br>Value changed to C<br>Value changed to D<br>done<br>Value changed again to D</pre><p><strong>7- How to convert cold flow into “shared / state flow” using “shareIn/stateIn” operator?!<br></strong>The shareIn / stateIn operator is useful in situations when there is a cold flow that is expensive to create and/or to maintain, but there are multiple subscribers that need to collect its values.</p><p><strong>For example:</strong><br>Consider a flow of messages coming from a backend over the expensive network connection, taking a lot of time to establish:</p><pre>fun backendMessagesFlow() = flow {<br>    // takes a lot of time<br>    connectToBackend()<br>    try {<br>      while (true) {<br>          emit(receiveMessageFromBackend())<br>      }<br>    } finally {<br>        disconnectFromBackend()<br>    }<br>}</pre><p>If this flow is directly used in the application, then every time it is collected a fresh connection is established, and it will take a while before messages start flowing. However, we can share a single connection and establish it eagerly like this:</p><pre>val messages: SharedFlow&lt;Message&gt; =<br> backendMessages.shareIn(scope, SharingStarted.Eagerly)</pre><pre>val messages: StateFlow&lt;State&gt; = <br>  backendMessages.stateIn(scope, SharingStarted.Eagerly, State.LOADING)</pre><h3><strong>Congratulations You have finished </strong>👏<strong>🥳</strong></h3><p>Hope You’ve enjoyed reading :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44b600faa2c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>