<?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[Corouteam - Medium]]></title>
        <description><![CDATA[A team of curious  developers from GDG Bari - Medium]]></description>
        <link>https://medium.com/corouteam?source=rss----22c28b866395---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Corouteam - Medium</title>
            <link>https://medium.com/corouteam?source=rss----22c28b866395---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 06:20:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/corouteam" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Exploring Kotlin Coroutines and Lifecycle Architectural Components integration on Android]]></title>
            <link>https://medium.com/corouteam/exploring-kotlin-coroutines-and-lifecycle-architectural-components-integration-on-android-c63bb8a9156f?source=rss----22c28b866395---4</link>
            <guid isPermaLink="false">https://medium.com/p/c63bb8a9156f</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Paolo Rotolo]]></dc:creator>
            <pubDate>Thu, 23 May 2019 15:56:43 GMT</pubDate>
            <atom:updated>2019-06-22T19:12:22.060Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>Exploring new Coroutines and Lifecycle Architectural Components integration on Android</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Px8Aru4UCSh-JZTSbONViw.png" /></figure><p>Google I/O brought various interesting things for Android Developers: there’s the cutting edge <strong>JetPack Compose</strong>, the new F̶l̶u̶t̶t̶e̶r̶ ̶i̶n̶ ̶K̶o̶t̶l̶i̶n̶ declarative toolkit to build UI using <strong>composable Widgets</strong>, but it’s still in early early stage of development and it’s not intended for production use in the short term.</p><p>Something that’s actually more interesting for Kotlin Developers, is the new <strong>integration between Coroutines and Arch Components</strong>, lifecycle and liveData in primis and by now I think you’ve already guessed what is the topic we’re going to cover in this article :)</p><p>First of all, to get all the new features, you need to use version <strong><em>androidx.lifecycle:*:2.2.0-alpha01 </em></strong>or more<strong><em> </em></strong>of the lifecycle libraries.</p><p>But that’s not all. If you look at the docs you’ll find out there’s a new Coroutine scope called <strong>lifecycleScope</strong> and a new <strong>LiveData building block</strong>.</p><p>Including that, is actually quite tricky… Searching online it’s not very hard to find comments like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*N7NL1Vk5p2tW2brFWh3kBA.png" /></figure><p>…or this…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*Dq4CfQy-F7iaqrfQBB71hA.png" /></figure><p>There’s in fact another library that Google silently released that enables those features called <strong>lifecycle-runtime-ktx </strong>that you need to import as well.</p><p>So, the full list of imports required to try all the features listed in this post is:</p><pre>def arch_version = &#39;2.2.0-alpha01&#39;</pre><pre>implementation &quot;androidx.lifecycle:lifecycle-extensions:$arch_version&quot;</pre><pre>implementation &quot;androidx.lifecycle:lifecycle-viewmodel-ktx:$arch_version&quot;</pre><pre>implementation &quot;androidx.lifecycle:lifecycle-livedata-ktx:$arch_version&quot;</pre><pre>implementation &quot;androidx.lifecycle:lifecycle-runtime-ktx:$arch_version&quot;</pre><blockquote>I’m assuming you’re already familiar with Coroutines basics on Android. If you’re not, check out this <a href="https://medium.com/androiddevelopers/coroutines-on-android-part-i-getting-the-background-3e0e54d20bb">awesome series of Medium posts</a> by <a href="https://medium.com/u/83518fe480be">Sean McQuillan</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*MeAzvIUCrkcBgGkd2TRBTw.gif" /></figure><h3>What’s new in androidx.lifecycle:*:2.2.0-alpha01</h3><h4>Coroutine Scope and ViewModelScope</h4><p>You probably know that <strong>Coroutines run in a scope</strong> that will handle for you useful things like <strong>get uncaught exceptions</strong> and <strong>cancellation</strong> to make sure you never leak a Coroutine.</p><p>If you need to call a suspending function from a ViewModel, instead of manually creating a new scope, there’s one already ready for you: <strong>viewModelScope i</strong>s bound to ViewModel’s lifecycle and <strong>will handle for you cancellation</strong> when the ViewModel onClear() is called. You can easily access this scope from an <strong>extension function</strong> available on <em>viewmodel-ktx</em> library.</p><p>Here you can see an example of a function to sign in the user using Firebase Auth.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/910ff3d3daaadb2ded168c977bdf72e7/href">https://medium.com/media/910ff3d3daaadb2ded168c977bdf72e7/href</a></iframe><p>Note that Firebase Auth’s method<em> signInWithEmailAndPassword</em> returns a <strong>Task</strong> that you can conveniently convert to a cancellable suspending function using <strong>await() </strong>from<em> </em><a href="https://github.com/Kotlin/kotlinx.coroutines/tree/master/integration/kotlinx-coroutines-play-services"><em>kotlinx-coroutines-play-services</em></a><em>.</em></p><h3>LifecycleScope</h3><p>Starting from <em>lifecycle-runtime-ktx:2.2.0-alpha1</em>, there is also a similar scope for all Lifecycle objects like Activities and Fragments. Again, <strong>all the coroutines in that scope will be canceled when the Lifecycle is destroyed</strong>.</p><p>So it would be:</p><pre>activity.lifecycleScope.launch {<br> // scope bound to Activity Lifecycle<br>}</pre><pre>fragment.lifecycleScope.launch {<br> // scope bound to Fragment Lifecycle <br>}</pre><pre>fragment.viewLifecycleOwner.launch{<br> // scope bound to Fragment View<br>}</pre><p>Be aware that <strong>lifecycleScope is convenient when dealing with UI events </strong>like, for example, showing a tip for the user and hiding it after a small delay.</p><pre>lifecycleScope.launch {<br>    <strong>delay</strong>(5000)<br>    <strong>showTip</strong>()<br>    <strong>delay</strong>(5000)<br>    <strong>hideTip</strong>()<br>}</pre><p>Without using Coroutines and lifecycleScope, this would be:</p><pre>val DELAY = 5000</pre><pre>Handler().postDelayed({<br>  <strong>showTip()</strong><br>    Handler().postDelayed({<br>      <strong>hideTip()</strong><br>    }, <strong>DELAY</strong>)<br>}, <strong>DELAY</strong>)</pre><p>You should <strong>not use lifecycleScope for other tasks </strong>like retrieving data from repositories or making long computations. This is because those scopes are bound to Activities and Fragments lifecycles and will cancel the coroutines inside them when, for instance, there’s a configuration change.</p><p><strong>In short, you will end up with your network request canceled if the user rotates the phone</strong>, defeating the whole purpose of a ViewModel behind an Activity. That’s why it’s better to call those methods inside the <strong>viewModelScope </strong>and<strong> let the activity only observe</strong> the LiveData value. We’ll come back to this later.</p><p>But that’s not all. <strong>You may want to run those coroutines only if your Lifecycle is in a certain state</strong>.</p><p>Let’s refresh our memory with all possible lifecycle states from Android docs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3_Ch9IJlgtDIi_mzYCyiQ.png" /></figure><p>Again, reading from the docs, you’ll notice that:</p><blockquote>When a <a href="https://developer.android.com/reference/androidx/fragment/app/Fragment.html">Fragment</a>state is saved via <a href="https://developer.android.com/reference/androidx/appcompat/app/AppCompatActivity.html#onSaveInstanceState(android.os.Bundle)">onSaveInstanceState()</a>, it&#39;s UI is considered immutable until <a href="https://developer.android.com/reference/androidx/lifecycle/Lifecycle.Event.html#ON_START">ON_START</a> is called. Trying to modify the UI after the state is saved is likely to cause inconsistencies in the navigation state of your application which is why <a href="https://developer.android.com/reference/androidx/fragment/app/FragmentManager.html">FragmentManager</a> throws an exception if the app runs a<a href="https://developer.android.com/reference/androidx/fragment/app/FragmentTransaction.html">FragmentTransaction</a> after state is saved.</blockquote><p>So if you need to run a FragmentTransaction inside your coroutine scope, you need your Fragment lifecycle to be at least<strong> STARTED.</strong></p><p>You can achieve this using<em> lifecycleScope.launchWhenStarted </em>to ensure your code will be called at the right time:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b09381f4e0fb27b59bf80f0fba8c936e/href">https://medium.com/media/b09381f4e0fb27b59bf80f0fba8c936e/href</a></iframe><h3>LiveData</h3><p>One of the big news introduced with livedata-2.1.0-alpha1, is<strong> interoperability between LiveData and Coroutines</strong>.</p><p>Let’s start with an example. You want to make a network request and expose the result to an Activity with a LiveData. The activity will start observing the LiveData which will be empty at first and will be notified when data is available from the network call.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0716262bca6ca21d94911804988315a3/href">https://medium.com/media/0716262bca6ca21d94911804988315a3/href</a></iframe><p>Starting from 2.2.0-alpha01, <strong>LiveData has a new building block </strong>that will automagically execute when the LiveData becomes active. No need to add that you’ll observe LiveData using a LifecycleOwner, so it will know when to stop executing and cancel the coroutines inside the building block. That’s very similar to lifecycleScope we’ve seen earlier.</p><p>Inside the LiveData building block, you can use <strong>emit()</strong> to set a value to the LiveData. Since LiveData allows only setting values from the main thread, emit() is always executed on this one.</p><p>So, the previous example will now become:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b57d697cf7c7774ae85598da578b9af3/href">https://medium.com/media/b57d697cf7c7774ae85598da578b9af3/href</a></iframe><p>This is a lot more simple and concise. Also note that we’re making a network request, so <strong>it would be better to run our suspending function on the IO Dispatcher</strong>. We can do that passing the dispatcher we want to use as parameter of the liveData block:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/744af346403c6aeca9de4eea7154da5b/href">https://medium.com/media/744af346403c6aeca9de4eea7154da5b/href</a></iframe><p>Simple as that. No need to switch dispatcher to Dispatchers.Main for the emit() function, since it will always automatically run on the main thread.</p><p>By the way, you might want to know that <strong>Retrofit now supports suspending functions</strong>. Well, <a href="https://github.com/square/retrofit">retrofit:2.5.1-SNAPSHOT</a> does, so if you’re more into stable releases, check out <a href="https://medium.com/u/8ddd94878165">Jake Wharton</a>’s <a href="https://github.com/JakeWharton/retrofit2-kotlin-coroutines-adapter">Kotlin Coroutine Adapter</a>.</p><p>Let’s see another example. Now you want to load first a<strong> cached copy</strong> of some data and then start getting the updated values, for example, from<strong> Firebase Database</strong>.</p><p>The flow would be:</p><ol><li>Emit cached copy (<em>Data</em>)</li><li>Emit Firebase Database data (<strong><em>LiveData</em></strong><em>&lt;Data&gt;</em>)</li></ol><p>Since <strong>Firebase already returns a LiveData</strong>, you’ll end with another LiveData in your ViewModel: the one from Firebase, and the one you’re building which has just emitted the cached data.</p><p>With <strong>emitSource() </strong>you can not only emit a single value, but attach your LiveData to another LiveData and start emitting from it. Anyway, each emit() or emitSource() call will remove the previously added source.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe384c81303be0c97d72624ecfdc597e/href">https://medium.com/media/fe384c81303be0c97d72624ecfdc597e/href</a></iframe><p>The activity that’s observing the <em>someData</em> object, will <strong>quickly receive the cached data</strong> on the device and update the UI. Then, the LiveData itself will take care of making the network request and<strong> replace the cached data with a new live stream </strong>of data, that will eventually trigger the Activity observer and update the UI with the updated info.</p><p>A similar example would be loading local data, fetching new data from a server and update cached data with the new one.</p><p>If you’re using Room, you probably know you can get LiveData out from a query:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd011f36d6de2e3ab1297fa285b55caa/href">https://medium.com/media/cd011f36d6de2e3ab1297fa285b55caa/href</a></iframe><p>In this case, you’re feeding the <em>post LiveData </em>with Room’s data. When an updated version of the post will be available, it will update the copy in the local database and Room will automatically emit the value.</p><p>We said early that LiveData, after a short <strong>timeout</strong>, will cancel all the coroutines that are still running when the attached lifecycle of the observer is destroyed, so no need to worry for that. You can adjust that timeout passing a Long as parameter with the milliseconds to wait before cancellation.</p><pre>var data = liveData(timeoutInMs = 10000) <strong>{<br>    </strong>val data = dataRepository.getData()<br>    emit(data)<br><strong>}</strong></pre><h3>Recap</h3><p>So now you have some new Coroutine Scopes, similar to <strong>viewModelScope</strong>,<strong> </strong>the<strong> lifecycleScopes</strong> bound to Activities, Fragments, View… in short every object that has a LifecycleOwner attached. You can use those to write UI related coroutines and eventually specify in which state of lifecycle run them.</p><p>You also have a new <strong>LiveData building block</strong> that comes with a Scope that lets you run coroutines and emit data from inside. Those coroutines will cancel after a small delay when the lifecycle of the object that is observing livedata is destroyed.</p><p><strong>But await(), there’s more!</strong></p><p>If you want to know more about Kotlin Coroutines with other Architectural Components here’s the <a href="https://developer.android.com/topic/libraries/architecture/coroutines">official documentation on Android Developers</a>. There’s also a good I/O session about the same topic <a href="https://www.youtube.com/watch?v=BOHK_w09pVA">available on YouTube</a>.</p><p><em>Happy coding, the </em><a href="https://github.com/orgs/corouteam/people"><em>Corouteam</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c63bb8a9156f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/corouteam/exploring-kotlin-coroutines-and-lifecycle-architectural-components-integration-on-android-c63bb8a9156f">Exploring Kotlin Coroutines and Lifecycle Architectural Components integration on Android</a> was originally published in <a href="https://medium.com/corouteam">Corouteam</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>