<?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 Marek Langiewicz on Medium]]></title>
        <description><![CDATA[Stories by Marek Langiewicz on Medium]]></description>
        <link>https://medium.com/@marek.langiewicz?source=rss-a5e37380c850------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4KHyxvBtdcON78a9.</url>
            <title>Stories by Marek Langiewicz on Medium</title>
            <link>https://medium.com/@marek.langiewicz?source=rss-a5e37380c850------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:05:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marek.langiewicz/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[Create a Clean-Code App with Kotlin Coroutines and Android Architecture Components — Part 3]]></title>
            <link>https://medium.com/elpassion/create-a-clean-code-app-with-kotlin-coroutines-and-android-architecture-components-part-3-f3f3850acbe6?source=rss-a5e37380c850------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3f3850acbe6</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[coroutine]]></category>
            <dc:creator><![CDATA[Marek Langiewicz]]></dc:creator>
            <pubDate>Thu, 23 Nov 2017 09:38:40 GMT</pubDate>
            <atom:updated>2020-11-16T15:54:57.577Z</atom:updated>
            <content:encoded><![CDATA[<h4>The View</h4><p>This is the third blog post about using <strong>Kotlin Coroutines</strong> and <strong>Android Architecture Components</strong> in one simple weather app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*cHuXxoxf-UCTwzz_RC69Gg.png" /></figure><p>Please read the first and second part if you haven’t yet</p><ul><li><a href="https://medium.com/elpassion/create-a-clean-code-app-with-kotlin-coroutines-and-android-architecture-components-f533b04b5431">Create a Clean-Code App with Kotlin Coroutines and Android Architecture Components</a></li><li><a href="https://medium.com/elpassion/create-a-clean-code-app-with-kotlin-coroutines-and-android-architecture-components-part-2-4f585050d7d7">Create a Clean-Code App with Kotlin Coroutines and Android Architecture Components — Part 2</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*DL--eDRDLPPCDR1nsAmILg.png" /></figure><p>We already have a working app implemented as the <a href="https://github.com/elpassion/crweather/blob/master/app/src/main/java/com/elpassion/crweather/MainModel.kt"><strong>MainModel</strong></a> class. Now we need to create the <strong>UI</strong> for it. This part will be android specific.</p><blockquote>Unfortunately, the <a href="https://github.com/elpassion/crweather/blob/master/app/src/main/java/com/elpassion/crweather/MainModel.kt">MainModel</a> is already a bit android specific because it uses <a href="https://developer.android.com/topic/libraries/architecture/livedata.html">LiveData</a> (and <a href="https://developer.android.com/topic/libraries/architecture/viewmodel.html">ViewModel</a>) from <a href="https://developer.android.com/topic/libraries/architecture/index.html">Android Architecture Components</a></blockquote><h3>06 View</h3><p>The <a href="https://github.com/elpassion/crweather/blob/master/app/src/main/java/com/elpassion/crweather/MainActivity.kt"><strong>MainActivity</strong></a> class represents a <strong>View</strong> that observes our <strong>Model</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*4fPIcW6e3qlwzZnlu7XsPw.png" /><figcaption><a href="https://github.com/elpassion/crweather/blob/master/app/src/main/java/com/elpassion/crweather/MainActivity.kt">https://github.com/elpassion/crweather/…../MainActivity.kt</a></figcaption></figure><p>Thanks to <a href="https://developer.android.com/topic/libraries/architecture/index.html"><strong>Android Architecture Components</strong></a>, our activity is really small. We don’t need to override any lifecycle methods like <a href="https://developer.android.com/reference/android/app/Activity.html#onStart()"><strong>onStart</strong></a>, <a href="https://developer.android.com/reference/android/app/Activity.html#onResume()"><strong>onResume</strong></a>, <a href="https://developer.android.com/reference/android/app/Activity.html#onPause()"><strong>onPause</strong></a>, <a href="https://developer.android.com/reference/android/app/Activity.html#onStop()"><strong>onStop</strong></a>, etc… We only need <a href="https://developer.android.com/reference/android/app/Activity.html#onCreate(android.os.Bundle)"><strong>onCreate</strong></a> to set things up.</p><p>In <a href="https://developer.android.com/reference/android/app/Activity.html#onCreate(android.os.Bundle)"><strong>onCreate</strong></a> method we set up content view, action bar, optionally the drawer, and the recycler view’s adapter. Just usual android stuff. Beside that we do two more things:</p><ul><li>We set up a click listener in navigation view with cities, so it invokes the <a href="https://github.com/elpassion/crweather/blob/0d2489b26d9e3d50ec84e87306f71610bbc12b2e/app/src/main/java/com/elpassion/crweather/DataTypes.kt#L23"><strong>SelectCity</strong></a> action on our <strong>model</strong> (line 25)</li><li>We initialize the <strong>model</strong> itself (line 28)</li></ul><p>Let’s take a closer look at the <strong>model</strong> initialization:</p><p>First line (32) gets the <strong>MainModel</strong> instance from <a href="https://developer.android.com/reference/android/arch/lifecycle/ViewModelProvider.html"><strong>ViewModelProvider</strong></a> which in turn is provided by <a href="https://developer.android.com/reference/android/arch/lifecycle/ViewModelProviders.html#of(android.support.v4.app.FragmentActivity)"><strong>ViewModelProviders.of(Activity)</strong></a> factory method. Here the <strong>Android Architecture Components</strong> library works a bit like <a href="https://google.github.io/dagger/"><strong>Dagger</strong></a>. It manages any <a href="https://developer.android.com/topic/libraries/architecture/viewmodel.html"><strong>ViewModel</strong></a> instances for us, and makes sure we get the same model instance after screen rotation (or any other device configuration change). This way, the new <strong>MainActivity</strong> instance can access the same model instance, “subscribe to” (or rather “<a href="https://developer.android.com/reference/android/arch/lifecycle/LiveData.html#observe(android.arch.lifecycle.LifecycleOwner,%20android.arch.lifecycle.Observer%3CT%3E)"><strong>observe</strong></a>”) the same app state <a href="https://developer.android.com/topic/libraries/architecture/livedata.html"><strong>LiveData</strong></a> objects, and display appropriate UI whenever the state changes.</p><blockquote>There is a nice detailed description of this “dependency injection” mechanism at the beginning of <a href="https://developer.android.com/topic/libraries/architecture/viewmodel.html"><strong>ViewModel</strong></a> class doc.</blockquote><p>Now, when we have our model instance, we can <strong>observe</strong> it. The <a href="https://developer.android.com/reference/android/arch/lifecycle/LiveData.html#observe(android.arch.lifecycle.LifecycleOwner,%20android.arch.lifecycle.Observer%3CT%3E)"><strong>LiveData.observe</strong></a> method takes the <strong>LifecycleOwner</strong> as a first parameter, so the <strong>LiveData</strong> knows when our activity is ready to receive state updates, and when it is destroyed. The <strong>LiveData</strong> class has a few <strong>guarantees</strong> that simplify the way we observe it:</p><ul><li>All state changes are dispatched on the main thread. This means we can immediately access android views and update displayed data.</li><li>Changes are dispatched only when the observer is <strong>active</strong>: its <a href="https://developer.android.com/reference/android/arch/lifecycle/Lifecycle.html"><strong>Lifecycle</strong></a> is in a <a href="https://developer.android.com/reference/android/arch/lifecycle/Lifecycle.State.html#STARTED"><strong>STARTED</strong></a> or <a href="https://developer.android.com/reference/android/arch/lifecycle/Lifecycle.State.html#RESUMED"><strong>RESUMED</strong></a> state. This means we won’t get any unnecessary updates when our activity is not visible.</li><li>New observer receives current value as soon as it becomes <strong>active</strong>. This means we will always have something to display as soon as our activity becomes visible.</li><li>When the observer is <a href="https://developer.android.com/reference/android/arch/lifecycle/Lifecycle.State.html#DESTROYED"><strong>DESTROYED</strong></a> the LiveData removes it from the observer list. This means we don’t have to remember to “unsubscribe” because it will be done automatically.</li><li>The order of all these life cycle related events is carefully designed so we never get infamous fragment transaction exceptions. Watch a few minutes of <a href="https://youtu.be/bEKNi1JOrNs?t=16m30s"><strong>this youtube presentation</strong> (from 16:30)</a> if you want more details.</li></ul><p>Here, in the <strong>MainActivity</strong>, we just set up <strong>LiveData</strong> observers to call our <strong>display…</strong> functions:</p><ul><li><strong>displayLoading</strong> Shows/hides the progress bar.</li><li><strong>displayCity</strong> Shows given city as selected in navigation view.</li><li><strong>displayCharts</strong> Shows given list of charts in recycler view (with some animations) — we will analyze it later.</li><li><strong>displayMessage</strong> Shows given (usually error) message (using a toast for simplicity).</li></ul><p>Unfortunately, <strong>LiveData</strong> (as well as <strong>ViewModel</strong>) is android specific, so it complicates testing. However, we could achieve better separation of concerns by implementing this “<strong>lifecycle aware</strong>” feature of <strong>LiveData</strong> with <a href="https://github.com/ReactiveX/RxJava"><strong>RxJava</strong></a>. It would require: some special <strong>Observable&lt;LifecycleEvent&gt;</strong> to signal lifecycle changes; some <a href="https://github.com/ReactiveX/RxJava/wiki/Subject"><strong>BehaviorSubject</strong></a> (to hold data and to return last known value on subscribe); <strong>switchMap</strong> operator (to wait until observer is active); <strong>takeUntil</strong> operator (to automatically <strong>unsubscribe</strong> at appropriate <strong>LifecycleEvent</strong>); and maybe more. We could also use a library, like <a href="https://github.com/trello/RxLifecycle"><strong>RxLifecycle</strong></a>. In <a href="https://www.elpassion.com/"><strong>El Passion</strong></a> we’ve already tried this solution with <a href="https://github.com/trello/RxLifecycle"><strong>RxLifecycle</strong></a> in one hackathon project (<a href="https://github.com/elpassion/teamcity-android-client"><strong>Teamcity Android Client</strong></a>), and it worked great.</p><blockquote>I guess, implementing all guarantees that LiveData gives us (like: no fragment transaction exceptions), could be tricky.</blockquote><p>To display the chart list we use a regular <strong>recycler view</strong> with very basic adapter setup. The interesting part is how we present a single item (<a href="https://github.com/elpassion/crweather/blob/0d2489b26d9e3d50ec84e87306f71610bbc12b2e/app/src/main/java/com/elpassion/crweather/DataTypes.kt#L6"><strong>Chart</strong></a>). We implement custom view class: <a href="https://github.com/elpassion/crweather/blob/0d2489b26d9e3d50ec84e87306f71610bbc12b2e/app/src/main/java/com/elpassion/crweather/ChartView.kt"><strong>ChartView</strong></a> with base class: <a href="https://github.com/elpassion/crweather/blob/0d2489b26d9e3d50ec84e87306f71610bbc12b2e/app/src/main/java/com/elpassion/crweather/CrView.kt"><strong>CrView</strong></a>. These two classes use <strong><em>suspendable functions</em></strong> and <strong><em>actors</em></strong> to implement chart animations. Let’s take a detailed look at it.</p><h3>07 CrView</h3><p>Redrawing UI in Android (as in other UI frameworks) is <strong>asynchronous</strong>. We call <a href="https://developer.android.com/reference/android/view/View.html#invalidate()"><strong>View.invalidate()</strong></a> to let the system know we want to redraw this view, then the system decides exactly when to call our <a href="https://developer.android.com/reference/android/view/View.html#onDraw(android.graphics.Canvas)"><strong>View.onDraw(Canvas)</strong></a> function to actually redraw the view. But what if we could <strong>pretend</strong> it is <strong>synchronous</strong>? We could then use ordinary control flow constructs like <strong>loops</strong> and just <strong>redraw</strong> the view for each animation frame in a <strong>loop</strong> (with some <strong>delay</strong> in between which would also <strong>pretend</strong> to be <strong>synchronous</strong>). We already know how to implement such (pretending to be synchronous) functions: <strong><em>suspending functions</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*5y_CE0RA2085bmicmiFNsw.png" /><figcaption><a href="https://github.com/elpassion/crweather/blob/master/app/src/main/java/com/elpassion/crweather/CrView.kt">https://github.com/elpassion/crweather/…../CrView.kt</a></figcaption></figure><p>The first thing we do here (line 8, 11, 28) is to allow user to set some code block to be executed on <a href="https://developer.android.com/reference/android/graphics/Canvas.html"><strong>Canvas</strong></a> every time the system calls <a href="https://developer.android.com/reference/android/view/View.html#onDraw(android.graphics.Canvas)"><strong>onDraw</strong></a>.</p><p>Next, we create the <strong><em>suspend fun redraw()</em></strong>. The implementation is actually pretty simple. All we want to do is to let the system know that we want to be redrawn (line 17), then <strong><em>suspend</em></strong> and save given continuation somewhere (line 18). Later, when the system calls onDraw, we check if we have some <strong>redraw</strong> call <strong><em>suspended</em></strong> and <strong>resume</strong> it if that is the case (line 29). We <strong>resume</strong> asynchronously so <strong>onDraw</strong> always ends fast.</p><p>That’s basically it. I’ve also added second <strong><em>suspendable</em></strong> function: <strong>draw</strong>, to show another possible way to use this class, but I don’t actually use it now.</p><p>Now let’s use <strong>CrView</strong> as a base class to implement a custom view that can display and animate weather charts.</p><h3>08 ChartView</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*JSJkIIMD8xoxKRxs4AIMWQ.png" /><figcaption><a href="https://github.com/elpassion/crweather/blob/master/app/src/main/java/com/elpassion/crweather/ChartView.kt">https://github.com/elpassion/crweather/…../ChartView.kt</a></figcaption></figure><p>We want to have public mutable property <strong>var chart: Chart</strong> with a custom setter that will cause new chart to appear (but not immediately — it should smoothly <strong>morph</strong> from current chart to the new one). Computations needed for animation and the drawing itself is handled by an <strong><em>actor</em></strong>, so the chart setter only sends all new charts to the <strong><em>actor</em></strong><em>’s</em> mailbox. We use the <strong>non-suspendable</strong> operation: <strong>offer</strong> (line 11) to send new charts to the <strong><em>actor</em></strong>. This will override any unprocessed chart in <strong><em>actor</em></strong><em>’s</em> mailbox with the new one.</p><p>Now, let’s take a look at the <strong><em>actor</em></strong> implementation.</p><h3>09 Second Actor</h3><p>We’ve already seen one <strong><em>actor</em></strong> in my previous blog post:</p><p><a href="https://blog.elpassion.com/create-a-clean-code-app-with-kotlin-coroutines-and-android-architecture-components-part-2-4f585050d7d7">Create a Clean-Code App with Kotlin Coroutines and Android Architecture Components — Part 2</a></p><p>This one is also implemented with the <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/ecda27fa01602e42922eadc16ef34b920b8006bb/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/Actor.kt#L82"><strong><em>actor</em></strong></a><em> </em><strong><em>coroutine builder</em></strong>, it uses the same <strong><em>coroutine dispatcher</em></strong>: <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/30dd5c129c493ca7b1a3b2b80437e8a7ec68f3ec/ui/kotlinx-coroutines-android/src/main/kotlin/kotlinx/coroutines/experimental/android/HandlerContext.kt#L28"><strong>UI</strong></a>, and the same channel type: <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/a74eb5f8b08e84f904e75aa71da4547c9178da8d/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/ConflatedChannel.kt"><strong>Channel.CONFLATED</strong></a>.</p><p>The idea is to keep the <strong>currentChart</strong> in a local variable (and the <strong>currentVelocities</strong> which represents speed and direction of every chart point animation); then to use an ordinary <strong>while</strong> loop in which we move the <strong>currentChart</strong> points just a little bit towards their final positions (<strong>destinationChart</strong>), <strong><em>redraw</em></strong> the view, then <strong><em>delay</em></strong> for a few millis, and repeat. This <strong>while</strong> loop takes care of animating the <strong>currentChart</strong> towards the <strong>destinationChart</strong> required by the user. This animation loop has to be placed inside another <strong>for</strong> loop which iterates through <strong><em>actor</em></strong><em>’s</em> mailbox and retrieves next <strong>destinationChart</strong>s offered by the user.</p><p>We have three <strong><em>suspension points</em></strong> here:</p><ul><li>Receiving the next chart from the mailbox (line 21).</li><li>Redrawing the view inside the inner <strong>while</strong> loop for every animation frame (line 30).</li><li>Suspending for 16 millis after every animation frame (line 31).</li></ul><p>I’ll skip the most boring implementation details (you can inspect it all on the <a href="https://github.com/elpassion/crweather"><strong>GitHub/CrWeather</strong></a>), except a few:</p><ul><li>At the beginning (line 19) we set up the <strong>CrView</strong> so that it draws <strong>currentChart</strong> every time the system wants to redraw the view.</li><li>The outer <strong>for</strong> loop iteration (line 21) almost never <strong>suspends</strong> because the inner <strong>while</strong> loop finishes only when there is already a new chart in the mailbox.</li><li>We use the same data class: <strong>Chart</strong> to remember velocities of <strong>currentChart</strong> points — every <strong>Point</strong> here represent a velocity vector. I’ve reused the <strong>Chart</strong> class just to keep the code short — it would be better to have a separate data structure for chart points velocities.</li><li>After getting a new destination chart, we <strong>copyAndReformat</strong> the <strong>currentChart</strong> (line 23) so it contains as many points as the new <strong>destinationChart</strong>.</li><li>The same goes with <strong>currentVelocities</strong> (line 25)</li><li>The <strong>moveABitTo</strong> extension function which actually moves the <strong>currentChart</strong> towards <strong>destinationChart</strong>, also changes velocities a bit, so the animation stabilizes after a while. Check the <a href="https://github.com/elpassion/crweather/blob/master/app/src/main/java/com/elpassion/crweather/ChartsUtils.kt"><strong>ChartsUtils.kt</strong></a> file for the implementation details.</li></ul><p>But what happens if the system abandons the particular <strong>ChartView</strong> instance? Will the <strong><em>actor</em></strong> compute new animation frames indefinitely?<br>It won’t, and here is why:</p><p>The <strong>redraw</strong> function calls the <strong>View.invalidate()</strong> and <strong><em>suspends</em></strong>, but the system will not call <strong>onDraw</strong> on this <strong>View</strong> object anymore. This means our <a href="https://github.com/JetBrains/kotlin/blob/8fa8ba70558cfd610d91b1c6ba55c37967ac35c5/libraries/stdlib/src/kotlin/coroutines/experimental/Coroutines.kt#L23"><strong>Continuation</strong></a> will <strong>not</strong> be <a href="https://github.com/JetBrains/kotlin/blob/8fa8ba70558cfd610d91b1c6ba55c37967ac35c5/libraries/stdlib/src/kotlin/coroutines/experimental/Coroutines.kt#L32"><strong><em>resumed</em></strong></a> at all. So, if the system has no live reference to the <strong>ChartView</strong>, then the reference to our <strong><em>suspendable point</em></strong> (the <strong>Continuation</strong>) is also lost, so it all can be garbage collected together with the <strong><em>actor</em></strong> itself. In general, when a suspended coroutine is forgotten (so no one keeps a reference to the <strong>Continuation</strong>), it will be correctly garbage collected.</p><p>Thanks to <strong>Kotlin Coroutines</strong> we can express the logic of animations and the logic of receiving new “morphing goals” in very natural way. The code shows how we think of this problem — we think: <em>“for every new chart… while(no new chart): morph the chart a bit, redraw current chart, wait for a little, repeat”</em>, and this is exactly how the implementation looks like. It’s also great that we can keep more state as local variables (like: <strong>currentChart</strong> and <strong>currentVelocities</strong>) under full control of specific <strong><em>actor</em></strong> — which (as every <strong><em>coroutine</em></strong>) runs sequentially.</p><blockquote>Notice that we mutate state from within the actor code that is accessed outside by CrView.onDraw. In general, the <a href="https://en.wikipedia.org/wiki/Actor_model">actor model</a> of concurrent computation forbids any shared state in favour of implementing all communication via actor’s mailboxes.</blockquote><p>It would also be very easy and natural to extend this <strong><em>actor</em></strong> logic, compose new animation phases, etc. We can easily implement small <strong><em>suspendable functions</em></strong> (with ordinary conditional statements, loops, etc) and just call those functions inside the <strong><em>actor</em></strong><em>‘s</em> code.</p><p>I think this style is simpler and a lot more composable than traditional object-oriented design — compare it to all those classes in Android <a href="https://developer.android.com/guide/topics/graphics/prop-animation.html"><strong>Property Animation</strong></a> system. Although all those <a href="https://developer.android.com/reference/android/animation/ValueAnimator.html">ValueAnimators</a>, <a href="https://developer.android.com/reference/android/animation/ObjectAnimator.html">ObjectAnimators</a>, <a href="https://developer.android.com/reference/android/animation/AnimatorSet.html">AnimatorSets</a>, different <a href="https://developer.android.com/reference/android/animation/TypeEvaluator.html">Evaluators</a> and <a href="https://developer.android.com/reference/android/animation/TimeInterpolator.html">Interpolators</a>, allow to create very sophisticated animations; implementing a similar system with <strong><em>suspendable functions</em></strong> would be more natural and would not require nearly as much boilerplate code.</p><h3>10 Conclusions</h3><p><strong>The Kotlin Coroutines</strong> can successfully compete with <a href="https://github.com/ReactiveX/RxJava"><strong>RxJava</strong></a> when it comes to fighting the <strong>Callback Hell</strong>, but on the other hand, it can cooperate with <strong>RxJava</strong> <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/master/reactive/kotlinx-coroutines-rx2/README.md"><strong>very well</strong></a> too.</p><p>In my opinion, we shouldn’t think of a <strong><em>suspendable function</em></strong> as just a function with some additional feature. This concept has a potential to greatly change the way we create our software in this more and more asynchronous world.</p><p>The second technology we’ve tested here — <strong>Android Architecture Components</strong> — is not such a big deal as the <strong>Kotlin Coroutines</strong> but it’s still quite useful. The <strong>LiveData</strong> class helps if you want some (easy to use) observable streams (and if you don’t want to include <strong>RxJava</strong>); and the <strong>ViewModel</strong> class helps if you want a simple “dependency injection” (and if you want to stop worrying about activity lifecycles and device configuration changes).</p><p>Software development on Android is becoming more and more exciting thanks to amazing libraries, tools, and (most importantly) <strong>Kotlin</strong> :-)<br>If you’re wondering about the future, I think <a href="https://github.com/svtk">Svetlana Isakova</a> from <a href="https://github.com/JetBrains">JetBrains</a> has the right answer for you (in two sentences): <a href="https://youtu.be/XEgibiHdJtQ?t=46m11s"><strong>The Future of Kotlin</strong></a> :-)</p><blockquote>Also check out <a href="https://medium.com/u/e821c45acf49">Andrey Breslav</a> post: <a href="https://blog.jetbrains.com/kotlin/2017/06/kotlin-future-features-survey-results/">Kotlin Future Features Survey Results</a></blockquote><p>Tap the 👏 button if you found this article useful!</p><p><strong>About the Author <br></strong>Marek is an Android Developer at EL Passion. You can find him on <a href="https://github.com/langara">GitHub</a> or at <a href="http://mareklangiewicz.pl/">his website</a>.</p><p>Find <a href="https://elpassion.workable.com/">EL Passion</a> on <a href="https://www.facebook.com/elpassion/">Facebook</a>, <a href="https://twitter.com/elpassion">Twitter</a> and <a href="https://www.instagram.com/elpassion/">Instagram</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3f3850acbe6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elpassion/create-a-clean-code-app-with-kotlin-coroutines-and-android-architecture-components-part-3-f3f3850acbe6">Create a Clean-Code App with Kotlin Coroutines and Android Architecture Components — Part 3</a> was originally published in <a href="https://medium.com/elpassion">EL Passion Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Clean-Code App with Kotlin Coroutines and Android Architecture Components — Part 2]]></title>
            <link>https://medium.com/elpassion/create-a-clean-code-app-with-kotlin-coroutines-and-android-architecture-components-part-2-4f585050d7d7?source=rss-a5e37380c850------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f585050d7d7</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[coroutine]]></category>
            <dc:creator><![CDATA[Marek Langiewicz]]></dc:creator>
            <pubDate>Thu, 26 Oct 2017 12:51:18 GMT</pubDate>
            <atom:updated>2020-11-16T15:52:01.003Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create a Clean-Code App with Kotlin Coroutines and Android Architecture Components — Part 2</h3><h4>All About Actors</h4><p>This is the second blog post about using <strong>Kotlin Coroutines</strong> and <strong>Android Architecture Components</strong> in one simple weather app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Ki5ncUrxCH0rtH9VL_pNmQ.png" /></figure><p>Please read the first part if you haven’t already:</p><p><a href="https://medium.com/elpassion/create-a-clean-code-app-with-kotlin-coroutines-and-android-architecture-components-f533b04b5431">Create a Clean-Code App with Kotlin Coroutines and Android Architecture Components</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*DL--eDRDLPPCDR1nsAmILg.png" /></figure><p>The most important part of our app is the <a href="https://github.com/elpassion/crweather/blob/master/app/src/main/java/com/elpassion/crweather/MainModel.kt"><strong>MainModel</strong></a>. Here we have the <strong><em>actor</em></strong> that actually decides when to request some data from network, when to use cached data, when to push new state (which is observed by our activity).</p><p>To understand how it works, at first let’s dive into <strong><em>actors</em></strong> idea in general.</p><h3>05 Actor</h3><p>There is a whole theory about concurrent computations with <strong><em>actors</em></strong> as universal primitives. You can read more about it on <a href="https://en.wikipedia.org/wiki/Actor_model"><strong>Wikipedia</strong></a>.</p><p>Basically, <strong><em>actor</em></strong> is a kind of “worker” that can sequentially do some work based on <strong>messages</strong> he waits for. The messages are sent via “mailbox” which in Kotlin is implemented as a <strong><em>channel</em></strong>.</p><p>So let’s dive into <strong><em>channels</em></strong> first :-)</p><h3>05.1 Channels Basics</h3><p>The <strong><em>channel</em></strong> concept is similar to a <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html"><strong>blocking queue</strong></a> but it has <strong><em>suspending</em></strong> operations instead of blocking ones, and it can be closed. We can <strong><em>send</em></strong> messages to it and <strong><em>receive</em></strong> messages from it. Both of these operations can cause a <strong><em>suspension</em></strong>. The <strong><em>send</em></strong> operation can <strong><em>suspend</em></strong> when the <strong><em>channel</em></strong> is full (it will resume when someone calls <strong><em>receive</em></strong> on this <strong><em>channel</em></strong>). The <strong><em>receive</em></strong> operation can <strong><em>suspend</em></strong> when the <strong><em>channel</em></strong> is empty (it will resume when someone calls <strong><em>send</em></strong> on this <strong><em>channel</em></strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*NPhpUK0C72u5ihbzsdSxVQ.png" /></figure><p>In Kotlin the <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/a74eb5f8b08e84f904e75aa71da4547c9178da8d/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/Channel.kt#L248"><strong><em>Channel&lt;E&gt;</em></strong></a> interface extends both:</p><ul><li><a href="https://github.com/Kotlin/kotlinx.coroutines/blob/a74eb5f8b08e84f904e75aa71da4547c9178da8d/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/Channel.kt#L30"><strong><em>SendChannel&lt;E&gt;</em></strong></a> base interface<br>which defines the <strong><em>suspend fun send(element: E)</em></strong> method</li><li><a href="https://github.com/Kotlin/kotlinx.coroutines/blob/a74eb5f8b08e84f904e75aa71da4547c9178da8d/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/Channel.kt#L104"><strong><em>ReceiveChannel&lt;E&gt;</em></strong></a> base interface<br>which defines the <strong><em>suspend fun receive(): E</em></strong> method</li></ul><p>These base interfaces also contain other not so essential (and not suspendable) methods:</p><ul><li><strong><em>SendChannel</em>.offer(element: E): Boolean<br></strong>adds an element to channel if possible, or return false if the channel is full</li><li><strong><em>SendChannel</em>.close(cause: Throwable? = null)<br></strong>closes the channel</li><li><strong><em>ReceiveChannel</em>.poll(): E?<br></strong>returns an element if available, or null if channel is empty</li><li>And some other (less important) methods…</li></ul><h3>Channels’ Types</h3><p><a href="https://github.com/Kotlin/kotlinx.coroutines/blob/a74eb5f8b08e84f904e75aa71da4547c9178da8d/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/RendezvousChannel.kt"><strong><em>RendezvousChannel&lt;E&gt;</em></strong></a> — it does not contain any internal buffer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*_yxb5stQgBEnd45ILUwPGg.png" /></figure><ul><li>every <strong><em>send</em></strong> invocation is <strong><em>suspended</em></strong> until someone else invokes <strong><em>receive</em></strong> (unless there is some <strong><em>receive</em></strong> operation already <strong><em>suspended</em></strong>)</li><li>every <strong><em>receive</em></strong> invocation is <strong><em>suspended</em></strong> until someone else invokes <strong><em>send</em></strong> (unless there is some <strong><em>send</em></strong> operation already <strong><em>suspended</em></strong>)</li></ul><p><a href="https://github.com/Kotlin/kotlinx.coroutines/blob/a74eb5f8b08e84f904e75aa71da4547c9178da8d/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/ArrayChannel.kt"><strong><em>ArrayChannel&lt;E&gt;</em></strong></a> — it does contain a fixed size buffer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*RkG2PTyXXlsfIaBj5I8jdQ.png" /></figure><ul><li><strong>send</strong> is <strong>suspended</strong> only if the buffer is full</li><li><strong>receive</strong> is <strong>suspended</strong> only if the buffer is empty</li></ul><p><a href="https://github.com/Kotlin/kotlinx.coroutines/blob/a74eb5f8b08e84f904e75aa71da4547c9178da8d/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/LinkedListChannel.kt"><strong><em>LinkedListChannel&lt;E&gt;</em></strong></a> — it contains linked-list buffer with unlimited capacity</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*-mS8duaY8gq3coGebsjAOQ.png" /></figure><ul><li><strong><em>send</em></strong> is never <strong><em>suspended </em></strong>— but it may throw <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/OutOfMemoryError.html">OutOfMemoryError</a><br>(well, everything can throw it if we run out of memory)</li><li><strong><em>receive</em></strong> is <strong><em>suspended</em></strong> when buffer is empty</li></ul><p><a href="https://github.com/Kotlin/kotlinx.coroutines/blob/a74eb5f8b08e84f904e75aa71da4547c9178da8d/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/ConflatedChannel.kt"><strong><em>ConflatedChannel&lt;E&gt;</em></strong></a> — it buffers at most one element and conflates all subsequent <strong><em>send</em></strong> invocations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*pc3TjuTsxxziOIBH1UrhRA.png" /></figure><ul><li><strong><em>send</em></strong> is never <strong><em>suspended</em></strong>, but new element overrides any old element waiting to be received</li><li><strong><em>receive</em></strong> is <strong><em>suspended</em></strong> when buffer is empty</li></ul><p>There are other types too, but we will skip them. Check the <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md#channels"><strong>Coroutines Guide</strong></a> if you want to know more.</p><p>We will use the <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/a74eb5f8b08e84f904e75aa71da4547c9178da8d/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/ConflatedChannel.kt"><strong><em>ConflatedChannel</em></strong></a> as our <strong><em>actor</em></strong>‘s mailbox.</p><h3>05.2 Actors Basics</h3><p>At many occasions it’s useful to have a <strong><em>coroutine</em></strong> with attached <strong><em>channel</em></strong> to <strong><em>send</em></strong> or <strong><em>receive</em></strong> some elements to/from other parts of the system. Usually, this <strong><em>coroutine</em></strong> only <strong><em>sends</em></strong> elements to the <strong><em>channel</em></strong> and those elements are <strong><em>received</em></strong> by the other part of the system (so our <strong><em>coroutine</em></strong> is a “<strong><em>producer</em></strong>”). Or the other way around: our <strong><em>coroutine</em></strong> only <strong><em>receives</em></strong> elements from a <strong><em>channel</em></strong> and someone else is <strong><em>sending</em></strong> elements to us through this <strong><em>channel</em></strong> (so our <strong><em>coroutine</em></strong> is a consumer, or rather an “<strong><em>actor</em>”</strong>).</p><p>To implement such scenarios we could create a <strong><em>suspendable function</em></strong> that takes such <strong><em>channel</em></strong> as a parameter and just uses it in its code. Then we would instantiate appropriate <strong><em>channel</em></strong> and use some <strong><em>coroutine builder</em></strong> to call our <strong><em>suspendable function</em></strong> with created <strong><em>channel</em></strong>. If it sounds like a bit too much to do, there are two special <strong><em>coroutine builders</em></strong> in <a href="https://github.com/Kotlin/kotlinx.coroutines"><strong>kotlinx.coroutines</strong></a> library for two most common scenarios (when we use <strong><em>channels</em></strong> as “mailboxes”):</p><ul><li><a href="https://github.com/Kotlin/kotlinx.coroutines/blob/ecda27fa01602e42922eadc16ef34b920b8006bb/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/Produce.kt#L89"><strong><em>produce</em></strong></a><em> </em>— Creates a <strong><em>coroutine</em></strong> with attached <strong><em>channel</em></strong> that <strong><em>coroutine</em></strong> itself uses to <strong><em>send</em></strong> elements into. The object returned from this <strong><em>coroutine</em></strong> implements the <strong><em>ReceiveChannel</em></strong> interface, so the user can consume elements produced by this <strong><em>coroutine</em></strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*X2nye2GveI83iLPeAqKlNw.png" /></figure><ul><li><a href="https://github.com/Kotlin/kotlinx.coroutines/blob/ecda27fa01602e42922eadc16ef34b920b8006bb/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/Actor.kt#L82"><strong><em>actor</em></strong></a> — Creates a <strong><em>coroutine</em></strong> with attached <strong><em>channel</em></strong> that <strong><em>coroutine</em></strong> itself uses to <strong><em>receive</em></strong> elements from. The object returned from this <strong><em>coroutine</em></strong> implements the <strong><em>SendChannel</em></strong> interface, so the user can <strong><em>send</em></strong> elements to this <strong><em>coroutine</em></strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*LOoUnHKTH3HLdD6OL7URog.png" /></figure><p>The <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/ecda27fa01602e42922eadc16ef34b920b8006bb/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/Actor.kt#L82"><strong><em>actor</em></strong></a><strong> <em>coroutine builder</em></strong> implementation in <a href="https://github.com/Kotlin/kotlinx.coroutines"><strong>kotlinx.coroutines</strong></a> looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/0*pjlLTNRxIhbqz-Ht." /><figcaption><a href="https://github.com/Kotlin/kotlinx.coroutines/blob/ecda27fa01602e42922eadc16ef34b920b8006bb/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/Actor.kt#L82">https://github.com/Kotlin/kotlinx.coroutines/...../Actor.kt#L82</a></figcaption></figure><p>Let’s analyze its parameters:</p><p><strong>context</strong> — The context for created <strong><em>coroutine<br></em></strong>(same as in all other <strong><em>coroutine builders</em></strong>).</p><p><strong>capacity</strong> — This number defines what type of <strong><em>channel<br></em></strong>will be created as a “mailbox” for this <strong><em>actor</em></strong>:</p><ul><li><strong><em>RendezvousChannel<br></em></strong>capacity = 0</li><li><strong><em>LinkedListChannel<br></em></strong>capacity = Channel.UNLIMITED</li><li><strong><em>ConflatedChannel<br></em></strong>capacity = Channel.CONFLATED</li><li><strong><em>ArrayChannel<br></em></strong>capacity = required (fixed) buffer size</li></ul><p><strong>start</strong> — The <strong><em>coroutine</em></strong> start option<br>(same as in all other <strong><em>coroutine builders</em></strong>).</p><p><strong>block</strong> — The <strong><em>coroutine</em></strong> code.<br>Here we provide the actual <strong><em>actor’s</em></strong> code.</p><p>The most important parameter is the last one. This is where we define what our <strong><em>actor</em></strong> will actually do. As you can see it’s a <strong><em>suspending function</em></strong> with receiver type: <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/7b10c942fd769b64d8c33fbbe5a667ab028230b3/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/Actor.kt#L26"><strong><em>ActorScope</em></strong></a>. This scope (besides extending the usual <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/7b10c942fd769b64d8c33fbbe5a667ab028230b3/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/CoroutineScope.kt#L26"><strong><em>CoroutineScope</em></strong></a>) extends the <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/a74eb5f8b08e84f904e75aa71da4547c9178da8d/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/Channel.kt#L104"><strong><em>ReceiveChannel</em></strong></a>. Thanks to that we have convenient access to our “mailbox” from inside our <strong><em>coroutine</em></strong> code. We can even use an ordinary <strong>for</strong> loop to iterate over elements <strong><em>sent</em></strong> to us. This loop will call the <strong><em>receive</em></strong> operation, so it will <strong><em>suspend</em></strong> the <strong><em>coroutine</em></strong> if the <strong><em>receive</em></strong> operation <strong><em>suspends</em></strong>.</p><p>Don’t worry if it sounds complicated — it will all be clear once we look at the actual code of the <strong><em>actor</em></strong> in our app. However, before that, let’s look at one last thing — type returned from the <strong><em>coroutine builder</em></strong>: <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/7b10c942fd769b64d8c33fbbe5a667ab028230b3/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/Actor.kt#L40"><strong>ActorJob</strong></a>. The <strong>ActorJob</strong> interface extends the <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/7b10c942fd769b64d8c33fbbe5a667ab028230b3/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/Job.kt#L61"><strong>Job</strong></a> interface — as all objects returned from <strong><em>coroutine builders</em></strong>, but it also extends the <strong><em>SendChannel</em></strong> interface. This way user can easily <strong><em>send</em></strong> elements to our <strong><em>actor</em></strong> using the <strong><em>send</em></strong> operation. User can also <strong>try</strong> to <strong><em>send</em></strong> elements to the channel using other <strong>non-suspendable</strong> operation: <strong>offer</strong>. It just returns <strong>false</strong> instead of <strong><em>suspending</em></strong> if it cannot <strong><em>send</em></strong> new element to this <strong><em>channel</em></strong>. This is what we will do in our app.</p><h3>05.3 Our First Actor</h3><p>Now, after dealing with some theory, we are ready to analyze the main <strong>actor</strong> in our app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*2frMeRS2T_3jwPpFeRInlQ.png" /><figcaption><a href="https://github.com/elpassion/crweather/blob/master/app/src/main/java/com/elpassion/crweather/MainModel.kt">https://github.com/elpassion/crweather/…../MainModel.kt</a></figcaption></figure><p>There are three important things we can see in the <strong><em>actor coroutine builder</em></strong> invocation (line 27):</p><ul><li>The type of our <strong><em>actor</em></strong>’s mailbox is the <a href="https://github.com/elpassion/crweather/blob/0d2489b26d9e3d50ec84e87306f71610bbc12b2e/app/src/main/java/com/elpassion/crweather/DataTypes.kt#L21"><strong>Action</strong></a>. It means that the user can <strong><em>send</em></strong> actions to our <strong><em>actor</em></strong> through its mailbox <strong><em>channel</em></strong>. Currently, there is only one possible action type: <a href="https://github.com/elpassion/crweather/blob/0d2489b26d9e3d50ec84e87306f71610bbc12b2e/app/src/main/java/com/elpassion/crweather/DataTypes.kt#L23"><strong>SelectCity</strong></a>, but this setup shows how it could be extended to other user actions.</li><li>We use the android specific <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/30dd5c129c493ca7b1a3b2b80437e8a7ec68f3ec/ui/kotlinx-coroutines-android/src/main/kotlin/kotlinx/coroutines/experimental/android/HandlerContext.kt#L28"><strong><em>UI</em></strong></a><em> </em><strong><em>coroutine dispatcher</em></strong> as a <strong><em>coroutine context</em></strong> — this ensures that all code of this <strong><em>actor</em></strong> will be executed on the android main thread. It allows us to easily change the app state by invoking the <a href="https://developer.android.com/reference/android/arch/lifecycle/MutableLiveData.html#setValue(T)"><strong>MutableLiveData.setValue</strong></a> function in <strong><em>actor’s</em></strong> code.</li><li>We could use the usual <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/ecda27fa01602e42922eadc16ef34b920b8006bb/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/CommonPool.kt#L31"><strong>CommonPool</strong></a><strong><em> coroutine dispatcher</em></strong> too, but then we would have to use <a href="https://developer.android.com/reference/android/arch/lifecycle/MutableLiveData.html#postValue(T)"><strong>MutableLiveData.postValue</strong></a> to change the app state.</li><li>We use the <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/a74eb5f8b08e84f904e75aa71da4547c9178da8d/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/ConflatedChannel.kt"><strong>Channel.CONFLATED</strong></a> as a “mailbox” <strong><em>channel</em></strong> type, so new user actions replace any unprocessed action. In our case, this is exactly what we want because if we haven’t selected city requested by the user yet and the user now wants to select another city — we should forget the old action and process the new one as soon as we are ready.</li></ul><p>Finally, let’s look at the actor’s code:</p><p>It is just a <strong>for</strong> loop iterating through “<strong>this</strong>”. As we remember “<strong>this</strong>” (receiver) of the <strong><em>actor’s</em></strong> code is the <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/7b10c942fd769b64d8c33fbbe5a667ab028230b3/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/Actor.kt#L26"><strong>ActorScope</strong></a> which extends the <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/a74eb5f8b08e84f904e75aa71da4547c9178da8d/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/Channel.kt#L104"><strong><em>ReceiveChannel</em></strong></a>. The <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/a74eb5f8b08e84f904e75aa71da4547c9178da8d/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/Channel.kt#L104"><strong><em>ReceiveChannel</em></strong></a> type has defined <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/a74eb5f8b08e84f904e75aa71da4547c9178da8d/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/Channel.kt#L177"><strong>iterator</strong></a>, so we can use it in <strong>for</strong> loops. Every iteration invokes the <strong><em>receive</em></strong> operation and possibly <strong><em>suspends</em></strong> if the mailbox <strong><em>channel</em></strong> is empty. So this is our first <strong><em>suspension point </em></strong>(IDE marks every suspension point with a green line crossing gray arrow). Iteration ends when the <strong><em>channel</em></strong> is closed. Inside the <strong>for</strong> loop we just check the type of the received action (currently it is always <strong>SelectCity</strong>) and do appropriate work.</p><p>Now, we have to implement the <strong>SelectCity</strong> user action. First, we change two parts of the app state immediately: we set the <strong>city</strong> LiveData value to the city name requested by user (so our view — MainActivity — displays new city as selected one), and the <strong>loading</strong> LiveData value to <strong>true</strong> (so our view displays some kind of progress indicator).</p><p>And finally, we <strong>try</strong> to gather the data for new selected city. I guess this line (nr 21/20) is the most important line in the app :-) First, we look for (fresh) charts for given city in the cache. The helper extension function on cache: <strong>getFreshCharts</strong> returns <strong>null</strong> if no fresh charts are found, and if that’s the case: we make a network call by invoking the <strong><em>getNewCharts</em></strong><em> </em><strong><em>suspension function</em></strong>. This is our second and last <strong><em>suspension point</em></strong> in the <strong><em>actor’s</em> code</strong>. After it resumes we set the state: <strong>charts</strong> LiveData value to new charts (also in line 21/20) and we set the <strong>loading</strong> LiveData value to <strong>false</strong> (line 16). If the <strong><em>getNewCharts suspension point</em></strong> resumes with an exception, we <strong>catch</strong> it and display the error message via <strong>message</strong> LiveData.</p><blockquote>There is a minor issue related to these messages — can you guess?<br>hint: think about device rotations :-)</blockquote><p>The <strong><em>suspend fun getNewCharts</em></strong> — besides calling our carefully prepared <strong><em>suspend fun getCityCharts</em></strong> from <strong>Repository</strong> — also saves new charts for a particular city in the cache.</p><p>That’s virtually all business logic of our app implemented in clean and concise way thanks to <strong><em>actors</em></strong> (and <strong><em>coroutines</em></strong> in general).</p><blockquote>Notice that we mutate external state from within the actor’s code. In general, the <a href="https://en.wikipedia.org/wiki/Actor_model"><strong>actor model</strong></a> of concurrent computation forbids any shared state in favour of implementing all communication via actor’s mailboxes.</blockquote><blockquote>If you’d like to know more about the actors, I’ve really enjoyed watching this video: <a href="https://youtu.be/7erJ1DV_Tlo"><strong>The Actor Model</strong></a>, with <a href="https://en.wikipedia.org/wiki/Erik_Meijer_(computer_scientist)">Erik Meijer</a>, <a href="https://en.wikipedia.org/wiki/Carl_Hewitt">Carl Hewitt</a>, and Clemens Szyperski</blockquote><p>The last part of the app is just a <strong>view</strong>. It is responsible for displaying current app <strong>state</strong>, and it forwards user actions to the main app <strong>model</strong> (which we’ve just discussed). You can read about <strong>view</strong> layer implementation in my next blog post:</p><p><a href="https://medium.com/elpassion/create-a-clean-code-app-with-kotlin-coroutines-and-android-architecture-components-part-3-f3f3850acbe6">Create a Clean-Code App with Kotlin Coroutines and Android Architecture Components — Part 3</a></p><p>Tap the 👏 button if you found this article useful!</p><p><strong>About the Author <br></strong>Marek is an Android Developer at EL Passion. You can find him on <a href="https://github.com/langara">GitHub</a> or at <a href="http://mareklangiewicz.pl/">his website</a>.</p><p>Find <a href="https://elpassion.workable.com/">EL Passion</a> on <a href="https://www.facebook.com/elpassion/">Facebook</a>, <a href="https://twitter.com/elpassion">Twitter</a> and <a href="https://www.instagram.com/elpassion/">Instagram</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f585050d7d7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elpassion/create-a-clean-code-app-with-kotlin-coroutines-and-android-architecture-components-part-2-4f585050d7d7">Create a Clean-Code App with Kotlin Coroutines and Android Architecture Components — Part 2</a> was originally published in <a href="https://medium.com/elpassion">EL Passion Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Clean-Code App with Kotlin Coroutines and Android Architecture Components]]></title>
            <link>https://medium.com/elpassion/create-a-clean-code-app-with-kotlin-coroutines-and-android-architecture-components-f533b04b5431?source=rss-a5e37380c850------2</link>
            <guid isPermaLink="false">https://medium.com/p/f533b04b5431</guid>
            <category><![CDATA[components]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutine]]></category>
            <dc:creator><![CDATA[Marek Langiewicz]]></dc:creator>
            <pubDate>Fri, 06 Oct 2017 07:08:16 GMT</pubDate>
            <atom:updated>2020-11-16T15:49:47.380Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Full demo weather app included.</strong></h4><p>Android development is evolving fast. A lot of developers and companies are trying to address common problems and create some great tools or libraries that can totally change the way we structure our apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4z7VB5NWS2PMqD5k0hG4vQ.png" /></figure><p>We get excited by the new possibilities, but it’s difficult to find time to rewrite our app to really benefit from a new programming style. But what if we actually start a new project? Which of those breakthrough ideas to employ? Which solutions are stable enough? Should we use RxJava extensively and structure our app with <strong>reactive-first mindset</strong>?</p><blockquote>The Cycle.js library (by <a href="https://medium.com/u/3ba9db42812d">André Staltz</a>) contains a great explanation of reactive-first mindset: <a href="https://cycle.js.org/streams.html">Cycle.js — Streams</a>.</blockquote><p>Rx is highly composable and it has great potential, but it’s so different from regular object-oriented programming style, that it will be really hard to understand for any developer without RxJava experience.</p><p>There are more questions to ask before starting a new project. For example:</p><ul><li>Should we use Kotlin instead of Java?<br>(actually here the answer is simple: <a href="https://www.quora.com/Does-Kotlin-make-Android-development-easier-and-faster/answer/Michal-Przadka?srid=Gu6q"><strong>YES</strong></a>)</li><li>Should we use experimental <strong>Kotlin Coroutines?<br></strong>(which, again, promote totally new programming style)</li><li>Should we use the new experimental library from Google:<br><strong>Android Architecture Components</strong>?</li></ul><p>It’s necessary to try it all first in a small app to really make an informed decision. This is exactly what <a href="https://github.com/elpassion/crweather">I did</a>, getting some useful insights in the process. If you want to find out what I learned, read on!</p><h3>About <a href="https://github.com/elpassion/crweather">The App</a></h3><p>The aim of the experiment was to create an <a href="https://github.com/elpassion/crweather">app</a> that downloads weather data for cities selected by user and then displays forecasts with graphical charts (and some fancy animations). It’s simple, yet it contains most of the typical features of Android projects.</p><p>It turns out that <strong>coroutines</strong> and <strong>architecture components</strong> play really well together and give us clean app architecture with good <strong>separation of concerns</strong>. Coroutines allow to express ideas in a natural and concise way. Suspendable functions are great if you want to code line-by-line the exact logic you have in mind — even if you need to make some asynchronous calls in between.</p><p>Also: <strong>no more jumping between callbacks</strong>. In this example app, coroutines also completely removed the need of using RxJava. Functions with suspendable points are easier to read and understand than some RxJava operator chains — these chains can quickly become too <em>functional. </em>;-)</p><blockquote>Having said that, I don’t think that RxJava can be replaced with coroutines in every use case. Observables give us a<strong> different kind of expressiveness</strong> that can not be mapped one to one to suspendable functions. In particular once constructed observable operator chain allow many events to flow through it, while a suspendable point resumes only once per invocation.</blockquote><p>Back to our weather app:<br>You can watch it in action below — but beware, I’m not a designer. :-)<br>Chart animations show how easily you can implement them arbitrarily by hand with simple coroutine — without any ObjectAnimators, Interpolators, Evaluators, PropertyValuesHolders, etc.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F1WUjdyGetkg%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D1WUjdyGetkg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F1WUjdyGetkg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/31577c4fe6c500c9384196b4eee7972b/href">https://medium.com/media/31577c4fe6c500c9384196b4eee7972b/href</a></iframe><p>The most important source code snippets are displayed below. However, if you’d like to see the full project, it’s available <a href="https://github.com/elpassion/crweather">on <strong>GitHub.</strong></a></p><p><a href="https://github.com/elpassion/crweather"><strong>https://github.com/elpassion/crweather</strong></a></p><p>There is not a lot of code and it should be easy to go through.</p><p>I will present the app structure starting from the network layer. Then I will move to the business logic (in the <a href="https://github.com/elpassion/crweather/blob/master/app/src/main/java/com/elpassion/crweather/MainModel.kt">MainModel.kt</a> file) which is <em>(almost)</em> not Android-specific. And finish with the UI part (which obviously is Android-specific).</p><p>Here is the general architecture diagram with text reference numbers added for your convenience. I will especially focus on <strong><em>green</em></strong> elements — <strong><em>suspendable functions</em></strong> and <strong><em>actors</em></strong> (an actor is a really useful kind of <strong><em>coroutine builder</em></strong>).</p><blockquote>The actor model in general is a mathematical model of concurrent computation — more about it in my next blog post.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*DL--eDRDLPPCDR1nsAmILg.png" /></figure><h3>01 Weather Service</h3><p>This service downloads weather forecasts for a given city from <a href="http://openweathermap.org/api">Open Weather Map</a> REST API.</p><p>I use simple but powerful library from <a href="https://github.com/square">Square</a> called <a href="http://square.github.io/retrofit/">Retrofit</a>. I guess by now every Android developer knows it, but in case you never used it: it’s the most popular HTTP client on Android. It makes network calls and parses responses to <a href="https://en.wikipedia.org/wiki/Plain_old_Java_object">POJO</a>. Nothing fancy here — just a typical Retrofit configuration. I plug in the <a href="https://github.com/square/retrofit/tree/master/retrofit-converters/moshi">Moshi</a> converter to convert JSON responses to data classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*QGvoMVNbR_nHjmn0WCCFsw.png" /><figcaption><a href="https://github.com/elpassion/crweather/blob/master/app/src/main/java/com/elpassion/crweather/OpenWeatherMapApi.kt">https://github.com/elpassion/crweather/…/OpenWeatherMapApi.kt</a></figcaption></figure><p>One important thing to note here is that I set a return types of functions generated by Retrofit to: <a href="https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit2/Call.java">Call</a>.</p><p>I use <a href="https://github.com/square/retrofit/blob/b3ea768567e9e1fb1ba987bea021dbc0ead4acd4/retrofit/src/main/java/retrofit2/Call.java#L48">Call.enqueue(Callback)</a> to actually make a call to Open Weather Map. I don’t use any <a href="https://github.com/square/retrofit/tree/master/retrofit-adapters">call adapter</a> provided by Retrofit, because I wrap the Call object in the <strong><em>suspendable function</em></strong> myself.</p><h3>02 Utils</h3><p>This is where we enter <strong>the (</strong><a href="https://www.youtube.com/watch?v=_Lvf7Zu4XJU"><strong>brave new</strong></a><strong>) <em>coroutines</em> world</strong>: we want to create a generic <strong><em>suspendable function</em></strong> that wraps a <a href="https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit2/Call.java">Call</a> object.</p><blockquote>I assume you know at least the very basics of coroutines. Please read the first chapter of <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md">Coroutines Guide</a> (written by <a href="https://medium.com/u/4762e889f8fc">Roman Elizarov</a>) if you don’t.</blockquote><p>It will be an extension function: <a href="https://github.com/elpassion/crweather/blob/9c3e3cb803b7e4fffbb010ff085ac56645c9774d/app/src/main/java/com/elpassion/crweather/CommonUtils.kt#L24"><strong><em>suspend</em> fun</strong> Call&lt;T&gt;.<strong>await()</strong></a> that invokes the <a href="https://github.com/square/retrofit/blob/b3ea768567e9e1fb1ba987bea021dbc0ead4acd4/retrofit/src/main/java/retrofit2/Call.java#L48">Call.enqueue(…)</a> (to actually make a network call), then <strong><em>suspends</em></strong> and later <strong><em>resumes</em></strong> (when the response comes back).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*T6QT9tRQbqOS9pKJfyh0og.png" /><figcaption><a href="https://github.com/elpassion/crweather/blob/master/app/src/main/java/com/elpassion/crweather/CommonUtils.kt">https://github.com/elpassion/crweather/…/CommonUtils.kt</a></figcaption></figure><p>To turn any asynchronous computation into a <strong><em>suspendable function,</em></strong> we use the <a href="https://github.com/JetBrains/kotlin/blob/8f452ed0467e1239a7639b7ead3fb7bc5c1c4a52/libraries/stdlib/src/kotlin/coroutines/experimental/CoroutinesLibrary.kt#L89"><strong>suspendCoroutine</strong></a> function from The Kotlin Standard Library. It gives us a <a href="https://github.com/JetBrains/kotlin/blob/8fa8ba70558cfd610d91b1c6ba55c37967ac35c5/libraries/stdlib/src/kotlin/coroutines/experimental/Coroutines.kt#L23"><strong>Continuation</strong></a> object which is kind of a universal callback. We just have to call its <a href="https://github.com/JetBrains/kotlin/blob/8fa8ba70558cfd610d91b1c6ba55c37967ac35c5/libraries/stdlib/src/kotlin/coroutines/experimental/Coroutines.kt#L32"><strong>resume</strong></a> method (or <a href="https://github.com/JetBrains/kotlin/blob/8fa8ba70558cfd610d91b1c6ba55c37967ac35c5/libraries/stdlib/src/kotlin/coroutines/experimental/Coroutines.kt#L38"><strong>resumeWithException</strong></a>) anytime we want our new <strong><em>suspendable function</em></strong> to resume (normally or by throwing an exception).</p><p>The next step will be to use our new <strong><em>suspend</em> fun</strong> Call&lt;T&gt;.<strong>await()</strong> function to convert asynchronous functions generated by Retrofit into convenient <strong><em>suspendable functions</em></strong>.</p><h3>03 Repository</h3><p>The Repository object is a source of the data (<a href="https://github.com/elpassion/crweather/blob/master/app/src/main/java/com/elpassion/crweather/DataTypes.kt">charts</a>) displayed in our app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*rie-ith-AXP8-ajuBiNdzw.png" /><figcaption><a href="https://github.com/elpassion/crweather/blob/master/app/src/main/java/com/elpassion/crweather/Repository.kt">https://github.com/elpassion/crweather/…/Repository.kt</a></figcaption></figure><p>Here we have some private <strong><em>suspendable functions</em></strong> created by applying our <strong><em>suspend</em> fun</strong> Call&lt;T&gt;.<strong>await()</strong> extension to weather service functions. This way all of them return ready to use data like Forecast instead of Call&lt;Forecast&gt;. Then we use it in our one public <strong><em>suspendable function</em></strong>: <strong><em>suspend</em> fun</strong> getCityCharts(city: String): List&lt;Chart&gt;. It converts the data from api to a ready to display list of charts. I use some custom extension properties on List&lt;DailyForecast&gt; to actually convert the data to List&lt;Chart&gt;. Important note: only <strong><em>suspendable functions</em></strong> can call other <strong><em>suspendable functions</em></strong>.</p><blockquote>We have the <a href="http://openweathermap.org/appid">appid</a> hardcoded here for simplicity. Please generate new appid <a href="http://openweathermap.org/appid">here</a> if you want to test the app — this hardcoded one will be automatically blocked for 24h if it is used too frequently by too many people.</blockquote><p>In the next step we will create the main app <strong>model</strong> (implementing the Android <a href="https://developer.android.com/topic/libraries/architecture/viewmodel.html"><strong>ViewModel</strong></a> architecture component), that uses an <strong><em>actor (coroutine builder)</em></strong> to implement the application logic.</p><h3>04 Model</h3><p>In this app we only have one simple model: <a href="https://github.com/elpassion/crweather/blob/master/app/src/main/java/com/elpassion/crweather/MainModel.kt"><strong>MainModel</strong></a><strong> : </strong><a href="https://developer.android.com/topic/libraries/architecture/viewmodel.html"><strong>ViewModel</strong></a> used by our one activity: <a href="https://github.com/elpassion/crweather/blob/master/app/src/main/java/com/elpassion/crweather/MainActivity.kt"><strong>MainActivity</strong></a><strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*2frMeRS2T_3jwPpFeRInlQ.png" /><figcaption><a href="https://github.com/elpassion/crweather/blob/master/app/src/main/java/com/elpassion/crweather/MainModel.kt">https://github.com/elpassion/crweather/…/MainModel.kt</a></figcaption></figure><p>This class represents the app itself. It will be instantiated by our activity (actually by the Android system <a href="https://developer.android.com/reference/android/arch/lifecycle/ViewModelProvider.html">ViewModelProvider</a>), but it will survive configuration changes such as a screen rotation — new activity instance will get the same model instance. We don’t have to worry about activity lifecycle here at all. Instead of implementing all those activity lifecycle related methods (onCreate, onDestroy, …), we have just one <strong>onCleared()</strong> method called when the user exits the app.</p><blockquote>To be precise <strong>onCleared</strong> method is called when the activity is <strong>finished</strong>.</blockquote><p>Even though we are not tightly coupled to activity lifecycle anymore, we still have to somehow publish current state of our app model to display it somewhere (in the activity). This is where the <a href="https://developer.android.com/topic/libraries/architecture/livedata.html"><strong>LiveData</strong></a> comes into play.</p><p>The <a href="https://developer.android.com/topic/libraries/architecture/livedata.html"><strong>LiveData</strong></a> is like <a href="https://github.com/ReactiveX/RxJava">RxJava</a> <a href="https://github.com/ReactiveX/RxJava/wiki/Subject"><strong>BehaviorSubject</strong></a> reinvented once again… It holds a mutable value that is <strong>observable</strong>. The most important difference is how we subscribe to it and we will see it later in the <a href="https://github.com/elpassion/crweather/blob/master/app/src/main/java/com/elpassion/crweather/MainActivity.kt">MainActivity</a>.</p><blockquote>Also LiveData doesn’t have all those powerful composable operators Observable has. There are only some simple <a href="https://developer.android.com/reference/android/arch/lifecycle/Transformations.html">Transformations</a>.</blockquote><blockquote>Another difference is that LiveData is Android-specific and RxJava subjects are not, so they can be easily tested with regular non-android JUnit tests.</blockquote><blockquote>Yet another difference is that LiveData is “lifecycle aware” — more about it in my next posts, where I present the <a href="https://github.com/elpassion/crweather/blob/master/app/src/main/java/com/elpassion/crweather/MainActivity.kt">MainActivity</a> class.</blockquote><p>In here we are actually using the <a href="https://developer.android.com/reference/android/arch/lifecycle/MutableLiveData.html"><strong>MutableLiveData</strong></a> : <a href="https://developer.android.com/topic/libraries/architecture/livedata.html">LiveData</a> objects that allow to push new values into it freely. The app <strong>state</strong> is represented by four LiveData objects: <strong>city</strong>, <strong>charts</strong>, <strong>loading</strong>, and <strong>message</strong>. The most important of these is the <strong>charts: LiveData&lt;List&lt;Chart&gt;&gt;</strong> object which represents current list of charts to display.</p><p>All the work of changing the app state and reacting to user actions is performed by an <strong><em>ACTOR</em></strong>.</p><p><strong><em>Actors</em></strong> are awesome and will be explained in my next blog post :-)</p><h3>Summary</h3><p>We have already prepared everything for our main <strong><em>actor</em></strong>. And if you look at the <strong><em>actor</em></strong> code itself — you can (kind of) see how it works even without knowing <strong><em>coroutines</em></strong> or <strong><em>actors</em></strong> theory. Even though it has only a few lines, it actually contains all important business logic of this app. The magic is where we call <strong><em>suspendable functions</em></strong> (marked by gray arrows with green line). One <strong><em>suspendable point</em></strong> is the iteration over user actions and second is the network call. Thanks to <strong><em>coroutines</em></strong> it looks like synchronous blocking code but it doesn’t block the thread at all.</p><p>Check out the second part where I explain <strong><em>actors</em></strong> (and <strong><em>channels</em></strong>) in detail:</p><p><a href="https://medium.com/elpassion/create-a-clean-code-app-with-kotlin-coroutines-and-android-architecture-components-part-2-4f585050d7d7">Create a Clean-Code App with Kotlin Coroutines and Android Architecture Components — Part 2</a></p><p>Tap the 👏 button if you found this article useful!</p><p><strong>About the Author <br></strong>Marek is an Android Developer at EL Passion. You can find him on <a href="https://github.com/langara">GitHub</a> or at <a href="http://mareklangiewicz.pl/">his website</a>.</p><p>Find <a href="https://elpassion.workable.com/">EL Passion</a> on <a href="https://www.facebook.com/elpassion/">Facebook</a>, <a href="https://twitter.com/elpassion">Twitter</a> and <a href="https://www.instagram.com/elpassion/">Instagram</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f533b04b5431" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elpassion/create-a-clean-code-app-with-kotlin-coroutines-and-android-architecture-components-f533b04b5431">Create a Clean-Code App with Kotlin Coroutines and Android Architecture Components</a> was originally published in <a href="https://medium.com/elpassion">EL Passion Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>