<?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 Abir Hasan Zoha on Medium]]></title>
        <description><![CDATA[Stories by Abir Hasan Zoha on Medium]]></description>
        <link>https://medium.com/@zoha131?source=rss-f085c0716dda------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ULuqzrDe65vyYs2m630Www.jpeg</url>
            <title>Stories by Abir Hasan Zoha on Medium</title>
            <link>https://medium.com/@zoha131?source=rss-f085c0716dda------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 08:20:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zoha131/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[Coroutine in Android: Working with Lifecycle]]></title>
            <link>https://medium.com/android-news/coroutine-in-android-working-with-lifecycle-fc9c1a31e5f3?source=rss-f085c0716dda------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc9c1a31e5f3</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[lifecycle]]></category>
            <dc:creator><![CDATA[Abir Hasan Zoha]]></dc:creator>
            <pubDate>Fri, 09 Aug 2019 10:00:24 GMT</pubDate>
            <atom:updated>2019-11-17T10:50:02.475Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a_zx-coDeDRzVioeQ4jSVg.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/jplenio-7645255/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3822149">Johannes Plenio</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3822149">Pixabay</a></figcaption></figure><p>In this series of blog posts, I am going to explore Kotlin Coroutine and it’s usage in the Android world.</p><ol><li><a href="https://medium.com/@zoha131/coroutine-basic-daf23bbd3c15?source=friends_link&amp;sk=ea7927169262a9a8c7691f9521c6bd15">Coroutine in Android: Basic</a></li><li>Coroutine in Android: Working with Lifecycle (You are here)</li><li><a href="https://zsmb.co/retrofit-meets-coroutines/">Coroutine in Android: Working with Retrofit</a> (credit: <a href="https://twitter.com/zsmb13">zsmb13</a>)</li><li>Coroutine in Android: Working with Room Database</li><li>Coroutine in Android: Working with Workmanager</li></ol><p>In the previous blog post, I have discussed the Basic of Kotlin Coroutine. In this blog post, I am going to discuss the coroutine support in LifeCycle library. I have assumed that you are familiar and have working experience with <a href="https://developer.android.com/topic/libraries/architecture/viewmodel">Lifecycle </a>library.</p><p>Lifecycle library has three main artifacts. These artifacts provide us with three main APIs to work with Coroutine.</p><ol><li><strong><em>LifecycleScope </em></strong>in <strong><em>lifecycle-runtime </em></strong>from version <em>2.2.0-alpha01</em></li><li><strong><em>ViewModelScope </em></strong>in <strong><em>lifecycle-viewmodel</em></strong> from version <em>2.1.0-beta01</em></li><li><strong><em>livedata </em></strong>in<strong><em> lifecycle-livedata </em></strong>from version <em>2.2.0-alpha01</em></li></ol><p>To have all these APIs available in your project, add the following dependencies in the <a href="https://zoha131.github.io/androidDependency/"><em>build.gradle</em></a> file:</p><pre>def livedata_version = &quot;2.2.0-alpha02&quot;<br>implementation &quot;androidx.lifecycle:lifecycle-viewmodel-ktx:$livedata_version&quot;<br>implementation &quot;androidx.lifecycle:lifecycle-runtime-ktx:$livedata_version&quot;<br>implementation &quot;androidx.lifecycle:lifecycle-livedata-ktx:$livedata_version&quot;</pre><h3>LifecycleScope</h3><p>A <strong><em>LifecycleScope </em></strong>is defined for each <a href="https://developer.android.com/topic/libraries/architecture/lifecycle"><strong><em>Lifecycle</em></strong></a> &amp; <a href="https://developer.android.com/topic/libraries/architecture/lifecycle#lco"><strong><em>LifecycleOwner </em></strong></a>object. Any coroutine launched in this scope is canceled when the <em>Lifecycle </em>is destroyed.</p><p>From <strong><em>Activity </em></strong>you can access LifecycleScope in two ways:</p><pre><em>lifecycle</em>.<em>coroutineScope</em>.<em>launch </em><strong>{...}<br></strong><em>lifecycleScope</em>.<em>launch </em><strong>{...}</strong></pre><p>And from <strong><em>Fragment </em></strong>you can access LifecycleScope in three ways:</p><pre><em>viewLifecycleOwner</em>.<em>lifecycleScope</em>.<em>launch </em><strong>{...}<br></strong><em>lifecycle</em>.<em>coroutineScope</em>.<em>launch </em><strong>{...}<br></strong><em>lifecycleScope</em>.<em>launch </em><strong>{...}</strong></pre><p>Regardless of how you access the LifesycleScope, you will get the same <em>CoroutineScope</em>.</p><p><em>LifecycleScope </em>is bound to <strong><em>Dispatcher.Main</em></strong>. That means if you don’t change Dispatcher explicitly all the coroutines inside LifecycleScope will be executed on the main thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*ah8KDWsRvt2i9jQ4SD5acw.png" /><figcaption>lifecycleScope</figcaption></figure><h4>Handling Exception in LifecycleScope</h4><p>LifecycleScope uses <a href="https://kotlinlang.org/docs/reference/coroutines/exception-handling.html#supervision"><strong><em>SupervisorJob</em></strong></a>. In the SupervisorJob, if any child coroutine failed then this failure is not propagated to any other siblings. But if the parent gets canceled then all the children get canceled.</p><p>A failure of a child job that was created using <strong><em>lifecycleScope.launch{…}</em></strong> can be handled via <strong><em>CoroutineExceptionHandler</em></strong>. The <strong><em>lifecycleScope.launch(…) </em></strong>takes an optional <strong><em>CoroutineExceptionHandler </em></strong>parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*7Obz_XXtE9Sj24d20iT8cA.png" /><figcaption>here exception in the second coroutine won’t stop the first coroutine. It will be handled by the <strong>CoroutineExceptionHandler</strong></figcaption></figure><p>Here one more thing I want to mention is that if you use nested <strong><em>launch{…}</em></strong> and pass handler on the nested <em>launch{…}</em> it won’t have any effect. Only if you call <strong><em>launch{…}</em></strong> using the <strong><em>lifecycleScope </em></strong>then the passed handler will handle the exception.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*O5kwvG-0RFe4NGodDXCW-Q.png" /><figcaption>only <strong>lifecycleScope.launch(…)</strong> use handler to handle Exception</figcaption></figure><p>A failure of a child job that was created using <strong><em>lifecycleScope.async{…}</em></strong> can be handled via <strong><em>Deferred.await</em></strong> on the resulting deferred value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*eHsAU55RdixzzNwgI1lgHg.png" /><figcaption>handling Exception on <strong>Deferred.await</strong> using a try-catch block</figcaption></figure><h4>Suspend Lifecycle-aware coroutines</h4><p>Alongside with the default coroutine builders, the <strong><em>lifecycleScope </em></strong>provides three special coroutine builders:</p><pre><em>lifecycleScope</em>.launchWhenCreated <strong>{...}<br></strong><em>lifecycleScope</em>.launchWhenStarted <strong>{...}<br></strong><em>lifecycleScope</em>.launchWhenResumed <strong>{...}</strong></pre><p><a href="https://developer.android.com/reference/androidx/lifecycle/Lifecycle.html"><strong><em>Lifecycle</em></strong></a><strong><em> </em></strong>also provides three special <em>suspending functions</em> to have the same functionalities: lifecycle.whenCreated, lifecycle.whenStarted, and lifecycle.whenResumed. You can call them from any suspending function or coroutine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*tFr32f-f4lEnaWGS9MmcaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*ZJ2TSsrQcLTOJ02xst_PaA.png" /><figcaption>Notice: here log from the coroutine was executed 2s after the onStart method called. Before onStart, the coroutine was suspended.</figcaption></figure><p>Any coroutine run inside these blocks is suspended if the <strong><em>Lifecycle </em></strong>isn’t at least in the minimal desired state. The example above contains a code block that runs only when the associated Lifecycle is at least in the STARTED state.</p><p>If the Lifecycle moves to a lesser state while the block is running, the block will be suspended until the Lifecycle reaches a state greater or equal to minState.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*euuJViVSEl1te7_LAncDqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*p2MDwThcewUQI2G3Wg-DhA.png" /><figcaption>Here the block from launchWhenStarted get’s suspended when the lifecycle moves to lesser State.</figcaption></figure><p>For simplicity you can remember that:</p><ol><li><strong><em>launchWhenCreated {…}</em></strong> gets suspended when <strong><em>onDestry()</em></strong> is called or user clear the app from backStack</li><li><strong><em>launchWhenStarted {…}</em></strong> gets suspended when <strong><em>onStop()</em></strong> is called</li><li><strong><em>launchWhenResumed {…} </em></strong>gets suspended when <strong><em>onPause() </em></strong>is called</li></ol><p>Note that this won’t affect any sub coroutine if they use a different <strong><em>CoroutineDispatcher</em></strong>. However, the block will not resume execution when the sub coroutine finishes unless the <strong><em>Lifecycle </em></strong>is at least in <strong><em>minState</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*G2qT_6BBzHN8qfs2T7Z0xA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*35shcmLbU1eexflHPwjreQ.png" /><figcaption>Here, the block from different Dispatcher continues to run even after the onStop method is called. But after returning from different Dispatcher the block from launchWhenStarted get suspended as the State of the lifecycle is less than Started.</figcaption></figure><h3>ViewModelScope</h3><p>A <strong><em>ViewModelScope </em></strong>is defined for each <strong><em>ViewModel </em></strong>in your app. Any coroutine launched in this scope is automatically canceled if the ViewModel is cleared.</p><p>From ViewModel, you can access the ViewModelScope by the extension property <strong><em>viewModelScope.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*qxyXbJgOy2myW6O8sKiOIA.png" /><figcaption>using <strong>viewModelScope</strong> inside any ViewModel</figcaption></figure><p>This <strong><em>ViewModelScope </em></strong>is bound to <strong><em>Dispatchers.Main</em></strong>, that means by default all code will be executed in the <strong><em>Main </em></strong>thread. And it uses the <strong><em>SupervisorJob. </em></strong>So the exception handling of <strong><em>ViewModelScope </em></strong>is the same as the <strong><em>LifecycleScope </em></strong>we have just learned before.</p><h3>Coroutines with LiveData</h3><p>In <strong><em>ViewModel, </em></strong>we mostly use <strong><em>LiveData </em></strong>to serve data from <em>ViewModel </em>to <em>Activity </em>or <em>Fragment</em>. We can get the <strong><em>LiveData </em></strong>asynchronously by using <strong><em>ViewModelScope</em></strong>. But to make our life easier <em>LiveCycle </em>library provides us <strong><em>liveData </em></strong>builder function. The <strong><em>liveData </em></strong>building block serves as a <a href="https://medium.com/@elizarov/structured-concurrency-722d765aa952"><em>structured concurrency primitive</em></a> between coroutines and <em>LiveData</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*k4wcPpGUup6ceWWozLDP1g.png" /><figcaption>emitting data from liveData builder function</figcaption></figure><p>The coroutine created by <strong><em>liveData </em></strong>uses <strong><em>Dispatchers.Main </em></strong>by default. That means by default every code inside <strong><em>liveData </em></strong>block will be executed in the <strong><em>Main</em></strong> thread.</p><p><strong><em>liveData </em></strong>builder function takes two optional param <strong><em>CoroutineContext</em></strong>, and <strong><em>TimeOut </em></strong>in millis. <strong><em>TimeOut </em></strong>is used to wait before cancellation.</p><blockquote>Note: Do not pass <strong><em>CoroutineContext </em></strong>here unless you really need to.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*6EPeskKyzBTvG3jhLcI_BA.png" /><figcaption>example with timeout &amp; context</figcaption></figure><h4><strong>The block inside liveData follows some special rules:</strong></h4><ol><li>The block inside <strong><em>liveData </em></strong>doesn’t start executing immediately. It starts executing when the returned <strong><em>LiveData </em></strong>is active.</li><li>If the <strong><em>LiveData </em></strong>becomes inactive while the block is executing, it will be canceled after <strong><em>TimeOut </em></strong>unless the <strong><em>LiveData </em></strong>becomes active again before that timeout. Any value emitted from a canceled block will be ignored.</li><li>After cancellation, if the <strong><em>LiveData </em></strong>becomes active again, the block will be re-executed<em> </em><strong><em>from the beginning</em></strong>.</li><li>If the block completes <strong><em>successfully </em></strong>or is canceled due to reasons other than <strong><em>LiveData </em></strong>becoming inactive, it will not be re-executed even after <strong><em>LiveData</em></strong> goes through the active inactive cycle.</li></ol><h4>emit(…)</h4><p>Inside <strong>liveData</strong><em> </em>building block, you can call <strong><em>emit(…)</em></strong> function to set the <strong><em>LiveData’s </em></strong>value. This function offers the main safety. That means you can call this function from any thread and each <strong><em>emit(…) </em></strong>call suspends the execution of the block until the <strong><em>LiveData </em></strong>value is set on the main thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*zCy-nEIwkDaBHFVeOhBCkQ.png" /><figcaption>calling emit(…) from different Dispatcher</figcaption></figure><p>You can also emit multiple values from the block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*Hdlqo8rtCGMoBe-_BECOwg.png" /><figcaption>calling emit(…) multiple times from a single liveData{…} block</figcaption></figure><h4>emitSource(…)</h4><p>Inside <strong><em>liveData </em></strong>building block, you can call <strong><em>emitSource(...)</em></strong> function to set a <strong><em>LiveData </em></strong>as a source for the <em>returned LiveData</em>. This is similar to <strong><em>MediatorLiveData.addSource(…). </em></strong>If the given <strong><em>LiveData </em></strong>get changed then the <em>returned LiveData</em> will also be changed automatically.</p><p>Calling <strong><em>emit(…)</em></strong> and <strong><em>emitSource(…)</em></strong> will remove any source that was yielded before via <strong><em>emitSource(…)</em></strong>. Also, this function returns <strong><em>DisposableHandle </em></strong>by which the source LiveData can be removed.</p><p>Like <strong><em>emit(...), </em></strong>this function also offers main safety. So you can call this function from any thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*cdwS0LMUVu-e1UenH459jw.png" /><figcaption>simple emitSource example</figcaption></figure><p>You can also call <strong><em>emitSource(..)</em></strong> multiple times from the block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*FpWoP2MJMkqqQG5eeYNODQ.png" /><figcaption>calling emitSource multiple times</figcaption></figure><h4>latestValue</h4><p><strong><em>latestValue </em></strong>is a property which you can access from <strong><em>liveData </em></strong>building block. It references the <em>current value</em> of the <strong><em>LiveData</em></strong>. If the block never emitted a value, <strong><em>latestValue</em></strong> will be null.</p><p>If the <strong><em>liveData </em></strong>building block gets re-executed because of TimeOut and If you would like to continue the operations based on where it was stopped last, you can use the <strong><em>latestValue</em></strong> property to get the latest value emitted by the block before it got canceled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*UGVynepraAOhTN35mC-ACw.png" /></figure><h4>liveData with <a href="https://developer.android.com/reference/androidx/lifecycle/Transformations">Transformations</a></h4><p>You can combine <strong><em>liveData </em></strong>with <strong><em>Transformations</em></strong>, as shown in the following example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*5pFgwg6Cq32jCcgspBJryA.png" /><figcaption>using liveData with Transformations</figcaption></figure><p>You can find the source code here:</p><p><a href="https://github.com/Zoha131/CoroutineLearning/tree/livedata">Zoha131/CoroutineLearning</a></p><p>In this blog post, I have documented my understanding of Kotlin Coroutine and Lifecycle Library. If you find it helpful please encourage me by clapping ❤️ &amp; following 😄. And feel free to comment if you have any observation or suggestion.</p><p>Follow me on =&gt; <a href="https://twitter.com/zoha131">Twitter </a>:: <a href="https://www.linkedin.com/in/zoha131/">LinkedIn </a>:: <a href="https://github.com/zoha131">Github</a></p><h4>Further Reading</h4><ol><li><a href="https://developer.android.com/topic/libraries/architecture/coroutines">Official Guide</a></li><li><a href="https://www.youtube.com/watch?v=BOHK_w09pVA">Understand Kotlin Coroutines on Android (Google I/O’19)</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc9c1a31e5f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/coroutine-in-android-working-with-lifecycle-fc9c1a31e5f3">Coroutine in Android: Working with Lifecycle</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coroutine Basic]]></title>
            <link>https://medium.com/android-news/coroutine-basic-daf23bbd3c15?source=rss-f085c0716dda------2</link>
            <guid isPermaLink="false">https://medium.com/p/daf23bbd3c15</guid>
            <dc:creator><![CDATA[Abir Hasan Zoha]]></dc:creator>
            <pubDate>Tue, 30 Jul 2019 13:27:20 GMT</pubDate>
            <atom:updated>2019-11-17T10:50:05.107Z</atom:updated>
            <content:encoded><![CDATA[<h3>Coroutine in Android: Basic</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_zfYoPfz16DLJPbH1hyCQ.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/Mariamichelle-165491/">Michelle Maria</a> from <a href="https://pixabay.com/photos/lake-garda-sirmione-949540/">Pixabay</a></figcaption></figure><p>In this series of blog posts, I am going to explore Kotlin Coroutine and it’s usage in the Android world.</p><ol><li>Coroutine in Android: Basic (You are here)</li><li><a href="https://medium.com/@zoha131/coroutine-in-android-working-with-lifecycle-fc9c1a31e5f3?sk=833f609566b8e0caaa2e8ae705ad4256">Coroutine in Android: Working with Lifecycle</a></li><li><a href="https://zsmb.co/retrofit-meets-coroutines/">Coroutine in Android: Working with Retrofit</a> (credit: <a href="https://twitter.com/zsmb13">zsmb13</a>)</li><li>Coroutine in Android: Working with Room Database</li><li>Coroutine in Android: Working with Workmanager</li></ol><p>Android development is evolving rapidly. Android development with java was full with so much boilerplate code. By the introduction of Kotlin, now we can be more focused on business logic. Same goes to the Kotlin coroutine. Before coroutine, we had to write so much boilerplate code to run asynchronous business logic. Now with a coroutine, we can write asynchronous and non-blocking code as if it was synchronous and blocking code.</p><h3>What is Kotlin Coroutine</h3><blockquote><em>“A coroutine is an instance of suspendable computation, conceptually similar to a thread, in the sense that it takes a block of code to run and has a similar life-cycle, it is created and started, but it is not bound to any particular thread. It may suspend its execution in one thread and resume in another one. Moreover, like a future or promise, it may complete with some result or exception.”</em></blockquote><p>Kotlin coroutine is a lightweight thread. Coroutines are way cheaper than actual Java Thread. So a developer can fire and forget a long number of coroutine without any headache. Coroutines are more like a task that can be executed in any thread.</p><p>Coroutine is a Kotlin language feature. But Kotlin standard library provides only minimal low-level APIs by which other libraries can utilize Coroutine feature. <strong><em>kotlinx.coroutines</em></strong> is a rich library for coroutines, developed by JetBrains. It contains a number of high-level coroutine-enabled primitives. If you want to add<strong><em> kotlinx.coroutnes</em></strong> in your project add the following <a href="https://zoha131.github.io/androidDependency/">gradle dependencies</a>:</p><pre><strong>dependencies</strong> <strong>{ <br>  ...<br></strong>  <strong>def</strong> coroutines_version <strong>=</strong> &quot;1.3.0-M2&quot;<br>  implementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version&quot;<br>  implementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version&quot;<br>  ...<br><strong>}</strong></pre><p><strong><em>suspend </em></strong>is the main keyword you will encounter to work with Kotlin Coroutine. suspend keyword is provided by the Kotlin standard library. Let’s discuss the keyword</p><h3>What is suspend</h3><p><strong><em>suspend </em></strong>is a Kotlin keyword which can be used before any kind of function. Any function marked with <strong><em>suspend </em></strong>keyword known as suspending function. Long-running (blocking) suspending function can be suspended from a thread and after completing the task on other thread can be resumed later on the caller thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*JGuJLqALrXDVbA5L_HKVUw.gif" /><figcaption>How suspending function works. <a href="https://medium.com/androiddevelopers/coroutines-on-android-part-i-getting-the-background-3e0e54d20bb">(image credit)</a></figcaption></figure><p>In the example above, <strong>get(…)</strong> will <strong>suspend</strong> the Coroutine before it starts the network request. The function <strong><em>get(...) </em></strong>will still be responsible for running the network request off the main thread. Then, when the network request completes, instead of calling a callback to notify the main thread, it can simply <strong>resume</strong> the Coroutine it suspended.</p><p>Enough talk. Now let’s write code with suspend and Coroutine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*SxB0cTXQ92ogLLkiDyOh7Q.png" /><figcaption>Defining suspending function</figcaption></figure><p>Here <strong><em>delay(...) </em></strong>is a suspending function that operates the same as <strong><em>Thread.sleep(...)</em></strong>. There is also an indication on the left of <strong><em>delay(millis)</em></strong> that this is a suspending function.</p><h4>Calling Suspending Function</h4><p>Here if we remove <strong>suspend </strong>keyword from <strong><em>logLater(…)</em></strong> function then we can’t call <strong><em>delay(...)</em></strong>. Because<strong><em> delay(...)</em></strong> is a suspending function and it is illegal to call suspending function from any normal function. Suspending functions can only be called from other suspending function and from Coroutine. To bridge the non-blocking world with blocking world we have to create Coroutine using coroutine builder. The most used coroutine builder is <strong><em>launch(...)</em></strong> function which is an extension function of <strong><em>CoroutineScope</em></strong> class.</p><blockquote>Suspending functions can only be called from other suspending function and from Coroutine.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*Cu1eQzaNzPmuUqJtwQMHhA.png" /><figcaption>A new coroutine has been created by GlobalScope.launch{..}</figcaption></figure><h4>Changing Thread in Coroutine</h4><p>Suspending function does not change Thread automatically. It is our responsibility to change Thread when we need. But in the Coroutine world, we don’t use Thread directly. We use <a href="https://kotlinlang.org/docs/reference/coroutines/coroutine-context-and-dispatchers.html"><strong>CoroutineDispatcher</strong> </a>to tell Coroutine to change the Thread. <strong>CoroutineDispatcher</strong> is responsible to determine what thread the corresponding coroutine uses for its execution.</p><p>The <strong><em>lunch(..)</em></strong><em> </em>function takes an optional <strong>CoroutineDispatcher </strong>parameter to change the Thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*GtBNKpdN8bb3UwYugs9AuQ.png" /><figcaption><strong>Dispatchers.Main</strong> has been used in the <strong><em>launch(..)</em></strong> function</figcaption></figure><p>We can also change the Dispatcher inside any suspending function using <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/with-context.html"><strong><em>withContext</em></strong></a><strong><em>(...)</em></strong> function. <strong><em>withContext(...)</em></strong> function returns the value of the last expression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*zEw0BBE4YlN05800VXSiNg.png" /><figcaption>Thread has been changed using <strong>Dispatcher</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*XAY96DBMnnD0Y36yIoNNxA.png" /><figcaption>Result of the above code. you can find that the Dispatcher of the Coroutine has not been changed in the <strong>logLater </strong>function but changed inside of the <strong>withContext{..}</strong></figcaption></figure><p>There are Three <strong>CoroutineDispatcher </strong>in the <strong><em>kotlinx.Coroutine</em></strong> library. They are:</p><pre><strong>+-----------------------------------+<br>|         Dispatchers.</strong><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-main.html"><strong>Main</strong></a><strong>          |<br>+-----------------------------------+</strong><br>| Main thread on Android, interact  |<br>| with the UI and perform light     |<br>| work                              |<br>+-----------------------------------+<br>| - Calling suspend functions       |<br>| - Call UI functions               |<br>| - Updating LiveData               |<br>+-----------------------------------+</pre><pre><strong>+-----------------------------------+<br>|          Dispatchers.</strong><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-i-o.html"><strong>IO</strong></a><strong>           |<br>+-----------------------------------+</strong><br>| Optimized for disk and network IO |<br>| off the main thread               |<br>+-----------------------------------+<br>| - Database*                       |<br>| - Reading/writing files           |<br>| - Networking**                    |<br>+-----------------------------------+</pre><pre><strong>+-----------------------------------+<br>|        Dispatchers.</strong><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-default.html"><strong>Default</strong></a><strong>        |<br>+-----------------------------------+</strong><br>| Optimized for CPU intensive work  |<br>| off the main thread               |<br>+-----------------------------------+<br>| - Sorting a list                  |<br>| - Parsing JSON                    |<br>| - DiffUtils                       |<br>+-----------------------------------+</pre><p>In Android, you normally interact with the UI which can’t be modified from other thread. So I recommend using <strong><em>Dispatchers.Main</em></strong> in the Coroutine builder. And if you need to change Thread then do this using <strong><em>withContext(...) </em></strong>inside Coroutine or any suspending function. And try not to touch UI elements from suspending function. Try to work with UI elements only from parent Coroutine.</p><h4>Concurrency in Coroutine</h4><p>Suspending functions are sequential by default. The codes inside suspending functions and Coroutine get executed one after another &amp; sequentially. If we see the <strong><em>logLater(...)</em></strong> suspending function, at first the first log get executed then it waits for the delay and then the second log gets executed. Everything in suspending world is sequential unless we tell explicitly to run the code concurrently.</p><p>To run code concurrently we need to use the <strong><em>async(...) </em></strong>builder method. The <strong><em>async(...)</em></strong> returns <strong><em>Deferred </em></strong>object and by using this object we can wait for the result. <strong><em>async(...)</em></strong> is an extension function on <strong><em>CoroutineScope</em></strong> class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*qwsrKq00NQQykR9bo2s0ag.png" /><figcaption>Coroutine without concurrency</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*HET_S-7eqCz0VpGyULSfqQ.png" /><figcaption>Result of the above code. It takes 10s to complete the code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*hYucgBMX7d1XahdbJf6F_w.png" /><figcaption>Coroutine with concurrency. <strong>coroutineScope{...} </strong>block has been used here to use <strong>async(...)</strong> inside a suspending function.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*bP1UL0MvXGcTgmWaXuWb4Q.png" /><figcaption>Result of the above code. It takes only 6s to complete. Also, notice second log message has been executed immediately after the first log message</figcaption></figure><p>If we see the log message we can find that without concurrency it took 10 seconds to complete the task but with <strong><em>async(...)</em></strong> function and explicit concurrency it took only 6 seconds to complete.</p><blockquote>Notice: <strong>coroutineScope{...} </strong>block has been used to call <strong>async(...)</strong> inside a suspending function.</blockquote><p><strong>async(...)</strong> can be called in many ways but it is recommended to call it only inside <strong>lunch{..}</strong> or <strong>coroutineScope{...}</strong> block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*xFyY4OUd1z4GoZ2fd0wb2g.png" /><figcaption>calling <strong>async(...)</strong> inside <strong>lunch{...} </strong>block. this is same as calling inside <strong>coroutineScope{...}</strong> block</figcaption></figure><h3>CoroutineScope</h3><p>By this time you should have noticed <strong>CoroutineScope </strong>multiple time. I have used <strong>GlobalScope </strong>to launch new coroutine which is an implementation of CoroutineScope. Now it is high time to learn about this.</p><p>I think of <strong><em>CoroutineScope </em></strong>as a boundary of the coroutines. CoroutineScope helps us to maintain the life-cycle of the coroutines. It has some extension functions by those we can easily create and cancel coroutines.</p><p>As of now, we have seen two coroutine builders <strong><em>launch(...) </em></strong>and <strong><em>async(...). </em></strong>Both of them are defined as extension function of <strong><em>CoroutineScope </em></strong>class to encourage developers to structure their coroutines.</p><pre>fun &lt;T&gt; <strong>CoroutineScope</strong>.async(...): Deferred&lt;T&gt; {...}<br>fun &lt;T&gt; <strong>CoroutineScope</strong>.launch(...): Job {...}</pre><p>To cancel coroutine we have an extension function:</p><p>fun <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html">CoroutineScope</a>.cancel(...): Unit {...}</p><h3>Structured Concurrency</h3><p>If you have read some blog posts or viewed some videos explaining Coroutine you most probably heard about the term <em>“Structured Concurrency”</em>.</p><p>To me, Structured Concurrency is the coding paradigm; it is the style of writing coroutine so that we have a minimum headache to maintain and understand the life-cycle of coroutine in our codebase.</p><p>If you are using any <strong><em>CoroutineScope </em></strong>other than <strong><em>GlobalScope </em></strong>and you call <strong><em>async(...)</em></strong> only inside <strong><em>launch{...}</em></strong> or <strong><em>coroutineScope{...}</em> </strong>block then you are writing coroutines with <strong><em>Structured Concurrency</em></strong>. And make sure you do not have <strong><em>Deferred </em></strong>object outside of coroutine.</p><blockquote>Using GlobalScope may lead to a memory leak.</blockquote><p>In the above example, I have used <strong>GlobalScope </strong>for simplicity. But in structured concurrency, you are highly discouraged to use <strong>GlobalScope</strong>. Using GlobalScope may lead to a memory leak. Luckily in Android, we don’t need to write our own custom CoroutineScope because <strong><em>Android Jetpack </em></strong>already provides us all the CoroutineScope we need. In the second blog post I am going to write about this.</p><p>Visit <a href="https://medium.com/@elizarov/structured-concurrency-722d765aa952">here </a>to learn more about Structured Concurrency.</p><h3>Coroutine API Annotations</h3><p>While we are familiar with <strong><em>Alpha</em></strong>, <strong><em>Beta </em></strong>and <strong><em>Stable </em></strong>release, the <strong><em>kotlinx.coroutines</em></strong> library takes a different approach to define its API stability. There are some annotations that indicate the state of the API.</p><pre><strong>+-----------------------------------+<br>|     ExperimentalCoroutinesApi     |<br>+-----------------------------------+</strong><br>| there is a chance that those      |<br>| declarations will be deprecated   |<br>| in the near future                |<br>+-----------------------------------+</pre><pre><strong>+-----------------------------------+<br>|       ObsoleteCoroutinesApi       |<br>+-----------------------------------+</strong><br>| these declarations will be        |<br>| deprecated in the future but      |<br>| there is no replacement for       |<br>| them yet                          |<br>+-----------------------------------+</pre><pre><strong>+-----------------------------------+<br>|       InternalCoroutinesApi       |<br>+-----------------------------------+</strong><br>| should not be used outside of     |<br>| `kotlinx.coroutines`              |<br>+-----------------------------------+</pre><pre><strong>+-----------------------------------+<br>|        </strong>    <strong>FlowPreview            |<br>+-----------------------------------+</strong><br>| Marks [<a href="https://medium.com/@elizarov/cold-flows-hot-channels-d74769805f9">Flow</a>]-related API as a     |<br>| feature preview   Flow preview    |<br>| has **no** backward compatibility |<br>| guarantees                        |<br>+-----------------------------------+</pre><p>There is also an interesting<a href="https://twitter.com/relizarov/status/1137006644007772162"> twitter thread</a> about Coroutine API annotations which you may find helpful.</p><p>You can find the source code here:</p><p><a href="https://github.com/Zoha131/CoroutineLearning/tree/basic">Zoha131/CoroutineLearning</a></p><p>In this blog post, I have documented my understanding of Kotlin Coroutine. If you find it helpful please encourage me by clapping ❤️ &amp; following 😄. And feel free to comment if you have any observation or suggestion.</p><p>Follow me on =&gt; <a href="https://twitter.com/zoha131">Twitter </a>:: <a href="https://www.linkedin.com/in/zoha131/">LinkedIn </a>:: <a href="https://github.com/zoha131">Github</a></p><h4>Further Reading</h4><ol><li><a href="https://kotlinlang.org/docs/reference/coroutines/coroutines-guide.html">Official Guide</a></li><li><a href="https://medium.com/androiddevelopers/coroutines-on-android-part-i-getting-the-background-3e0e54d20bb">Coroutines on Android (part I)</a></li><li><a href="https://www.youtube.com/watch?v=P7ov_r1JZ1g">Android Suspenders by Chris Banes</a></li><li><a href="https://www.youtube.com/watch?v=jT2gHPQ4Z1Q">Exploring Coroutines in Kotlin by Venkat Subramariam</a></li><li><a href="https://www.youtube.com/watch?v=_hfBv0a09Jc">Introduction to Coroutines by Roman Elizarov</a></li><li><a href="https://android.jlelse.eu/coroutines-basic-terminologies-and-usage-b4242bd1b2a4">Android Kotlin Coroutines: Basic Terminologies &amp; Usage</a></li><li><a href="https://proandroiddev.com/kotlin-coroutines-patterns-anti-patterns-f9d12984c68e">Kotlin Coroutines patterns &amp; anti-patterns</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daf23bbd3c15" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/coroutine-basic-daf23bbd3c15">Coroutine Basic</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CoordinatorLayout Basic]]></title>
            <link>https://medium.com/android-news/coordinatorlayout-basic-8040c74cf426?source=rss-f085c0716dda------2</link>
            <guid isPermaLink="false">https://medium.com/p/8040c74cf426</guid>
            <category><![CDATA[design-support-library]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[coordinatorlaout]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Abir Hasan Zoha]]></dc:creator>
            <pubDate>Mon, 12 Mar 2018 19:20:20 GMT</pubDate>
            <atom:updated>2018-06-11T06:21:43.847Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*oLRK2odVbVmqmavFzMzSBw.gif" /><figcaption>CoordinatorLayout in Action</figcaption></figure><p>CoordinatorLayout is a super-powered <a href="https://developer.android.com/reference/android/widget/FrameLayout.html">FrameLayout</a>.</p><p>CoordinatorLayout is a general-purpose container that allows for coordinating interactive behaviorsbetween its children.CoordinatorLayout manages interactions between its children, and as such needs to contain all the Views that interact with each other. The two general cases supported by CoordinatorLayout are:</p><ul><li>As a top-level content layout (meaning CoordinatorLayout is at the root of all views within an activity or fragment).</li><li>As a container for a specific interaction with one or more child views.</li></ul><p>By specifying <a href="https://developer.android.com/reference/android/support/design/widget/CoordinatorLayout.Behavior.html">Behaviors</a> for child views of a CoordinatorLayout you can provide many different interactions within a single parent and those views can also interact with one another.</p><h4>Important XML Attributes</h4><ul><li><strong>android:layout_gravity</strong>: Specifies the gravity of the child relative to the parent. If you specify an Anchor using <strong>app:layout_anchor, </strong>then this attribute would be ignored. And you have to use <strong>app:layout_anchorGravity </strong>to position the child. Do not use both of these together in any view. It may cause of unexpected result.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*uNEoD36-T_JFySQJhfeUIQ.png" /><figcaption>FAB without <strong>android:layout_gravity</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*W4aW-5ZUwj033bIVGs2WlQ.png" /><figcaption>FAB with <strong>android:layout_gravity=”bottom|end”</strong></figcaption></figure><ul><li><strong>app:layout_anchor</strong>: This attribute can be set on children of the CoordinatorLayout to attach them to another view. The value would be the <strong>id</strong> of an anchor view that this view should position relative to. Note that, the anchor view can be <strong>any</strong> child View (a child of a child of a child of a <em>CoordinatorLayout</em>, for example).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*YK5-_Xr_FWhN0wkzBXjc4w.png" /><figcaption>FAB with just <strong>app:layout_anchor=”@id/appbar” </strong>but wihtout <strong>app:layout_anchorGravity</strong></figcaption></figure><ul><li><strong>app:layout_anchorGravity: </strong>Specifies how an object should position relative to an anchor, on both the X and Y axes, within its parent’s bounds.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*_C6qzpZQSqr_Z7VkBCimgQ.png" /><figcaption>FAB with <strong>app:layout_anchorGravity=”bottom|end”</strong></figcaption></figure><ul><li><strong>app:layout_insetEdge: </strong>Specifies how this view insets the CoordinatorLayout and make some other views dodge it. The child consumes the area of the screen it occupies and other children should not be placed in that area. Bottom is the default insetEdge<strong> </strong>of <strong>SnackBar</strong></li><li><strong>app:layout_dodgeInsetEdges: </strong>Specifies which edges of the child should be offset by insets. Bottom is the default dodgeInsetEdges of <strong>FAB </strong>button. <a href="https://medium.com/@rusinikita/simple-view-dodging-with-coordinatorlayout-f13cc32e0de6">Learn More</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*dgu0UvltxlKVBJYS7I05hQ.gif" /><figcaption>The button don’t have <strong>dodgeInsetEdge </strong>but the FAB button has</figcaption></figure><ul><li><strong>app:layout_behavior: </strong>The class name of a Behavior class defining special runtime behavior for this child view. <strong>AppBarLayout </strong>and <strong>FAB </strong>button have default behavior attached to them. This is most important attributes of CoordinatorLayout . I have talked about this in another <a href="https://medium.com/@zoha131/coordinatorlayout-behavior-basic-fd9c10d3c6e3">blog post</a>.</li></ul><p>In some tutorial on the internet you may see that CoordinatorLayout has <a href="http://developer.android.com/reference/android/view/View.html#attr_android:fitsSystemWindows"><strong>android:fitsSystemWindows</strong></a><strong>=&quot;true&quot; attribute. </strong>You may wonder why should we use this attribute. You can find you answer <a href="https://medium.com/google-developers/why-would-i-want-to-fitssystemwindows-4e26d9ce1eec">here </a>and <a href="https://medium.com/@azizbekian/windowinsets-24e241d4afb9">here</a>.</p><p>That’s all for the basic. I have planned to post series on Material Component. So follow me if you don’t wanna miss my future post.</p><p>If this post is helpful, please clap for me.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8040c74cf426" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/coordinatorlayout-basic-8040c74cf426">CoordinatorLayout Basic</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fun with “scanf” in c]]></title>
            <link>https://medium.com/@zoha131/fun-with-scanf-in-c-3d7a8d310229?source=rss-f085c0716dda------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d7a8d310229</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Abir Hasan Zoha]]></dc:creator>
            <pubDate>Wed, 24 Jan 2018 19:58:42 GMT</pubDate>
            <atom:updated>2018-01-24T20:16:13.709Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Qfo3Bpp4GmyAxn-kykyykA.png" /></figure><p>If <strong><em>Code::Blocks</em></strong> is installed in your PC then you definitely know about <strong><em>‘scanf’. </em></strong>In this blog post I am going to write some fun facts about ‘scanf’, that you may not know about. Without any further talking let’s begin with the basic use of scanf:</p><p><strong>Basic use:</strong> Using basic string format and address of variable you can easily get user input from console.</p><pre>char a;<br>int b;<br>float c;<br>double d;<br>char s[20];</pre><pre>scanf(&quot;%c %d %f %lf %s&quot;, &amp;a, &amp;b, &amp;c, &amp;d, s);</pre><p><strong>“ * ” in scanf: </strong>Sometimes, you may need to exclude some character or number from user input. Suppose, the input is <strong><em>30/01/2018 </em></strong>and you want to get day, month, year separately as integer. You can achieve this, using <strong><em>“ * ” </em></strong>in string format.</p><pre>int day,month,year;<br>scanf(&quot;%d%*c%d%*c%d&quot;, &amp;day, &amp;month, &amp;year);</pre><p>Here, <strong><em>%c</em></strong> is character type specifier and <strong><em>%*c</em></strong> means one character would be read from the console but it wouldn’t be assigned to any variable. Here we excluded two <strong><em>“/”</em></strong> from the input.</p><p><strong><em>%*c</em></strong> would exclude one character. <strong>Remember,</strong> <strong><em>‘/n</em></strong>’ and <strong><em>‘/t’</em></strong> are single characters.</p><p><strong><em>%*d</em></strong> would exclude one integer.</p><p><strong><em>%*f</em></strong> would exclude one float.</p><p><strong><em>%*s</em></strong> would exclude one word.</p><p><strong>Number in scanf: </strong>Sometimes, we need to limit the number of digit in integer or float, number of character in string. We can achieve this by adding an integer(&gt;0) in the string format.</p><pre>int a;</pre><pre>scanf(&quot;%5d&quot;, &amp;a);</pre><p>The code above, would take just first 5 digit as input. Any digits after 5th one would be ignored. If the integer has less that 5 digits, then it would be taken as it is.</p><p><strong>%5c</strong> would take exact 5 characters as input. <strong>Remember,<em> </em></strong>if you take 5 character as input and want to store in an array, then the array size must not be less than 6. This means, the extra position is reserved for a null character `\0`. Otherwise, you may face some unexpected difficulties.</p><p><strong>%5d</strong> would take an integer of at most 5 digits.</p><p><strong>%5f</strong> would take a float type number of at most 5 digits or 4 digits and one “ . ” as input.</p><p><strong>%5s</strong> would take a string of at most 5 non white-space characters as input.</p><p><strong>[set] in scanf: </strong>You can achieve<strong> </strong><a href="https://stackoverflow.com/questions/15664664/scanf-regex-c"><strong>regular expression</strong></a> like flavor in scanf using <strong>[set]</strong> in string format. This method does not work with integer or float type. Using <strong>[set], </strong>you can only take character type input.</p><pre>char str[100];</pre><pre>scanf(&quot;%[^\n]&quot;, str);</pre><p><strong>%[^\n]</strong> would take all characters in a single line as input. You may know that, whenever we press <strong>Enter</strong> in keyboard, then <strong>“\n”</strong> character is written in the console. Here, <strong>“^”</strong> means up-to and <strong>“\n”</strong> means new line and finally, [^\n] means take input up-to new line.</p><p>Similarly, %[^5] would take all characters as input up-to 5. If you write “abcde fghk5k zaq” in the console, then just “abcde fghk” would be taken as input.</p><p><strong>%[0–9]</strong> would take just number characters as input. If you write “1234abc567” in the console, then just first numbers “1234” would be taken as input.</p><p>Similarly, %[a–z] would take just small letter alphabets as input. If you write “abc12ijkl” in the console, then just first small letters “abc” would be taken as input.</p><p><strong>%[123]</strong> would just take any combination of 1, 2, 3 as input. Anything other than 1,2,3 would be ignored. If you write “1123390123” in the console then just first “11233” would be taken as input.</p><p><strong>Combination of all: </strong>You can use any combination of <strong>“ * ”</strong>, <strong>number</strong> and <strong>[set]</strong> in scanf.</p><pre>char str[100];</pre><pre>scanf(&quot;%*[^:]%*2c%[^\n]&quot;, str);</pre><p>If you write the following in the console:</p><pre><em>Any combination: You are free to use any combination.</em></pre><p>Then only <strong>“<em>You are free to use any combination.”</em></strong><em> </em>would be stored in <strong>str</strong> variable. Here,</p><p><em>“Any combination” </em>this would be removed by `<strong>%*[^:]`</strong></p><p>“<em>: ” </em>this, a colon and a space total two character would be removed by `<strong>%*2c`</strong></p><p><strong>Return Value: </strong>Another fun fact of <strong>scanf </strong>is that, it has return type of integer. That means whenever we take input from console using scanf function, it returns an integer value which indicates, how many values are stored to the variables.</p><pre>int a, b, c;</pre><pre>c = scanf(&quot;%d %*d %d&quot;, &amp;a, &amp;b);</pre><pre>printf(&quot;%d\n&quot;, c);</pre><p>The code above would print 2. Although three integer would be scanned from console, only 2 value would be stored in the variable.</p><p>You can use the return value in<strong><em> if-statement</em></strong> to overcome any EOF(End of File) error.</p><p>To learn more about scanf, visit <a href="http://en.cppreference.com/w/c/io/fscanf">here</a>.</p><p>Special thanks to <a href="https://www.facebook.com/nowrozislam.pranto">Nowroz Islam</a> for helping me with the concepts.</p><p>English is not first language. So, if you find any mistake or have any suggestion feel free to comment. Happy coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d7a8d310229" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Keyboard Shortcuts in JavaFx]]></title>
            <link>https://medium.com/@zoha131/handling-keyboard-shortcuts-in-javafx-2972ba950a48?source=rss-f085c0716dda------2</link>
            <guid isPermaLink="false">https://medium.com/p/2972ba950a48</guid>
            <category><![CDATA[keyboard-shortcuts]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[javafx]]></category>
            <dc:creator><![CDATA[Abir Hasan Zoha]]></dc:creator>
            <pubDate>Thu, 18 Jan 2018 09:58:40 GMT</pubDate>
            <atom:updated>2018-01-18T12:58:09.559Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaFX accepts two types of keyboard shortcuts.</p><ol><li>Keyboard shortcut, that is associated with a control, and pressing its key combination sends an <strong>ActionEvent </strong>to the control. This is called <strong>Mnemonic .</strong></li><li>Keyboard shortcut, that is <strong>not </strong>associated with a control, but rather to a task. This is called <strong>Accelerator.</strong></li></ol><h3>Using Mnemonic</h3><p>It is very easy to set mnemonic key to a control that is subclass of <a href="https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Labeled.html">Labeled</a> class.</p><p><strong>Method 1:</strong></p><p>To add mnemonic key all you need is to add an underscore ( _ ) in the text content. The first underscore would be removed and the character following it would be set as the mnemonic key for the control.</p><pre>Button btn1 = new Button(&quot;_Mnemonic&quot;);<br>Button btn2 = new Button(&quot;Mnem_onic&quot;);</pre><p>Now you can send ActionEvent to <strong><em>btn1 </em></strong>by pressing “Alt+M” and <strong><em>btn2 </em></strong>by pressing “Alt+O”. Using this method you can just use those keys which are present in the text content of the labeled control.</p><p><strong>Method 2:</strong></p><p>You can also add mnemonic key to a control programmatically.</p><p>To add mnemonic using java code, first you need to create an object of <em>KeyCombination </em>class.</p><p><strong>Remember:</strong> <em>KeyCombination </em>is an abstract class. To create an object you can use either <em>KeyCodeCombination </em>or <em>KeyCharacterCombination </em>class. And you have to use <em>“KeyCombination.ALT_DOWN” </em>as second parameter otherwise it won’t work.</p><pre>Button btn = new Button(&quot;Mnemonic&quot;);</pre><pre>KeyCombination kc = new KeyCodeCombination(KeyCode.P, KeyCombination.ALT_DOWN);</pre><pre>KeyCombination kp = new KeyCharacterCombination(&quot;P&quot;, KeyCombination.ALT_DOWN);</pre><pre>//here kc and kp both are same</pre><p>Second, you have to create an object of <em>Mnemonic </em>class.</p><pre>Mnemonic mn = new Mnemonic(btn, kc); // you can also use kp</pre><p>Third, you have to add the <em>Mnemonic </em>object to the scene.</p><pre>scene.addMnemonic(mn);</pre><p>Now you can send ActionEvent to <strong><em>btn </em></strong>by pressing “Alt+P”. Using this method you can use any key as <em>Mnemonic key</em>.</p><p><strong>Note:</strong> you have to make sure that the <em>mnemonicParsing </em>property for the control is set to true. However, for most of the labeled controls, the <em>mnemonicParsing</em> is set to true by default.</p><h3>Using <strong>Accelerator</strong></h3><p>The Scene class maintains an <em>ObservableMap&lt;KeyCombination,<br>Runnable&gt;</em>, whose reference can be obtained using the <em>getAccelerators() </em>method.</p><p>To add accelerator key, first you have to create an object of <em>KeyCombination </em>class.</p><pre>KeyCombination kc = new KeyCodeCombination(KeyCode.Z, KeyCombination.<em>CONTROL_DOWN</em>);</pre><p>Second, you have to create an object of <em>Runnable.</em></p><pre>Runnable rn = ()-&gt; System.<em>out</em>.println(&quot;Accelerator key worked&quot;);</pre><p>Third, you have to put the references in the Accelerators map of the scene.</p><pre>scene.getAccelerators().put(kc, rn);</pre><p>Now, if you press “Ctrl + Z”, then the tasks of the Runnable object would be executed.</p><p>If you find any mistake or have any suggestion feel free to comment. Happy coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2972ba950a48" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>