<?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 Alfredo Cerezo Luna on Medium]]></title>
        <description><![CDATA[Stories by Alfredo Cerezo Luna on Medium]]></description>
        <link>https://medium.com/@acerezoluna?source=rss-771f79a5b93d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gj5bnjOFPlGUYtlV.</url>
            <title>Stories by Alfredo Cerezo Luna on Medium</title>
            <link>https://medium.com/@acerezoluna?source=rss-771f79a5b93d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:26:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@acerezoluna/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[Testing ViewModels: The Journey]]></title>
            <link>https://medium.com/microsoft-mobile-engineering/testing-viewmodels-the-journey-c6d7747b316b?source=rss-771f79a5b93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6d7747b316b</guid>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[livedata]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[coroutine]]></category>
            <dc:creator><![CDATA[Alfredo Cerezo Luna]]></dc:creator>
            <pubDate>Wed, 08 Jul 2020 14:33:48 GMT</pubDate>
            <atom:updated>2020-07-09T10:05:20.304Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZpoUKljTVizDNlhw_J6nA.jpeg" /></figure><p>Testing <a href="https://developer.android.com/topic/libraries/architecture/viewmodel">ViewModels</a> and <a href="https://developer.android.com/topic/libraries/architecture/livedata">LiveData</a> based logic synchronously and sequentially can bring some hidden consequences; on some occasions, it will be desirable to check if the steps the system takes to reach a specific state are correct.</p><h4>Long story</h4><p>Those times where asynchronous code was a nightmare for every Android developer seems to be very far away. <a href="https://developer.android.com/kotlin/coroutines">Coroutines</a> now offer a great tool to manage async code, and Google is working hard to improve the Android tooling. <br>But great power comes with great responsibilities, and we need to worry about testing our asynchronous code more than ever.</p><h4>An example of asynchronous code</h4><p>Google recommends using LiveData, ViewModels, and Coroutines to architect our apps. LiveData offers a convenient bridge to send information to our UI, ViewModel helps us to persist our data and separate concerns between business logic and presentation logic, and Coroutines are a lightweight tool to handle asynchronous code in a sequential programming style.</p><p>Let’s take a look at a possible example of this through an app that requests information from the network and presents it to the user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f35cc1f95aff42c939de220914c054b6/href">https://medium.com/media/f35cc1f95aff42c939de220914c054b6/href</a></iframe><p>We define three states for our data:</p><ul><li><strong>Success</strong>: indicating that the network request ended and the data is available to be consumed.</li><li><strong>Loading</strong>: indicating that we are executing the network request, and the information is not yet ready to use.</li><li><strong>Error</strong>: indicating that something went wrong.</li></ul><blockquote>The ViewModel will decide, keep and push the current state to the UI using the LiveData and, for the sake of simplicity, handle the network request.</blockquote><p>So when the app starts the UI controller (Activity) asks the ViewModel to provide some data, the ViewModel sends through the LiveData a <strong>Loading</strong> state to the UI to display a loading indicator, and it launches a coroutine to perform an asynchronous network call to get the requested data by the UI. After some time, once the data is downloaded and ready, the ViewModel pushes a <strong>Success</strong> state to remove the loading indicator and present the information, or if something went wrong, an <strong>Error</strong> state.</p><h4>Asynchronous code</h4><p>We use a background process to execute the network call to prevent the UI thread from blocking, and keep the app responsive to the user interaction; to do this, we perform the request inside a coroutine bound to the ViewModel’s lifecycle using <a href="https://developer.android.com/topic/libraries/architecture/coroutines#viewmodelscope"><strong>viewModelScope</strong></a>.</p><h4>The problem</h4><p>If we want the coroutine to run on a thread different than the UI thread, we need to specify a Dispatcher that our coroutine will use, to do so, we have two alternatives:</p><ul><li>Define right away the dispatcher when we launch the coroutine. In this case, the dispatcher should be injected into the class (this will help to write tests for the code; we will talk about that in a minute).</li><li>Or, we can use the dispatcher that the VideModel defines by default and rely on a suspending function that handles the dispatcher.</li></ul><p>In the first case (and in the second depending on which tools we use), our tests could be unreliable for the following reason:</p><ul><li>If we execute code that contains an asynchronous operation in a test, then the system will use a different thread other than the test thread to execute the coroutine.</li><li>At this point, the coroutine and the test will be running in two different threads. The test thread won’t wait or suspend until the coroutine ends and returns the information, and it will reach the verification step too soon. In the best scenario, the data won’t be ready sometimes, failing, and making out test non-deterministic or flaky.</li></ul><p>This is why we need to find a way to run our code inside a test sequentially in the same thread, this guarantees that the test result will always be the same.</p><p>So paradoxically, we ended up needing to turn asynchronous code into synchronous for testing.</p><h4>Building synchronous tests</h4><p>We got a couple of tools that will help us running synchronously asynchronous code.</p><ul><li><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/-test-coroutine-dispatcher/"><strong>TestCoroutineDispatcher</strong></a><strong>:</strong> this is a particular dispatcher that will execute scheduled actions immediately, one great thing of this dispatcher is that it runs using virtual time that we can pause and modify to inspect the state of execution in different points of time.</li><li><a href="https://developer.android.com/reference/android/arch/core/executor/testing/InstantTaskExecutorRule"><strong>InstantTaskExecutorRule</strong></a><strong>:</strong> JUnit test rule that swaps the background executor used by the <a href="https://developer.android.com/topic/libraries/architecture">Architecture Components</a> with a different one that executes everything synchronously.</li></ul><p>If we combine both tools, we can achieve synchronous tests that execute deterministically, check this excellent <a href="https://www.youtube.com/watch?v=KMb0Fs8rCRs&amp;vl=en">talk</a> to understand how it works, but in a few words:</p><p><em>We can use the TestCoroutineDispatcher to run our tests in a single thread and inject it into our ViewModels to guarantee that our asynchronous code runs in the same thread that the test does.</em></p><p>Or, if we decided to use the scope that the ViewModel provides to launch our coroutines, then we should use the InstantTaskExecutionRule to run any coroutine launched in the ViewModel in a Dispatcher defined by us, in this case, the TestCoroutineDispatcher.</p><p>Following any of the two alternatives, or combining both, our tests and methods will run synchronously in the same thread, which will always return the same result.</p><h4><strong>The hidden issue</strong></h4><p>With the architecture before described, we mainly want to test if our ViewModel computes and sends the right state through the LiveData:</p><ul><li>When the app starts, the LiveData should contain a Loading state.</li><li>When the data download ends, the LiveData should provide a Success state with the data.</li><li>When something fails, the LiveData should return an Error state.</li></ul><p>Ultimately, we are checking snapshots of the LiveData state during the execution of the test. This brings a hidden issue: <em>what if in between two states an unexpected value is pushed?</em> As LiveData only returns the last value, we wouldn’t detect this problem.</p><p>There is an easy solution for this; we can record all events received through the LiveData:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d20450ec8976d385aa8a69e47a196189/href">https://medium.com/media/d20450ec8976d385aa8a69e47a196189/href</a></iframe><p>This way, we will have a stored LiveData timeline where we can check if the stream of events received on it is the one that we expect, or if on the contrary, something sneaked into the LiveData causing glitches or unknown issues.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1e01a463bbf346670a214e08a13c71f/href">https://medium.com/media/f1e01a463bbf346670a214e08a13c71f/href</a></iframe><p><strong>Conclusion<br></strong>Designing good tests is hard, luckily we can always infer some patterns to test those parts of our system that repeats consistently like presenters, controller, or ViewModels.</p><p>In this post, we have seen three tools: TestCoroutineDispatcher, InstantTaskExecutionRule, and LiveData observer pattern that we could use to build the basic structure for our ViewModel tests.</p><p>Happy testing!</p><p><em>Thanks to </em><a href="https://medium.com/u/8317e8033cb6"><em>Cesar Valiente</em></a><em> and </em><a href="https://medium.com/u/8a50f70a2229"><em>Antonio C</em></a><em> for the feedback on this article.<br>Thanks to </em><a href="https://medium.com/u/6fbd7b94b75e"><em>Vipul Shah</em></a><em> for finding an error in the observeForTesting extension ;).</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6d7747b316b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/microsoft-mobile-engineering/testing-viewmodels-the-journey-c6d7747b316b">Testing ViewModels: The Journey</a> was originally published in <a href="https://medium.com/microsoft-mobile-engineering">Microsoft Mobile Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detekt in 2018]]></title>
            <link>https://medium.com/@acerezoluna/detekt-in-2018-5f9b898c12d8?source=rss-771f79a5b93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f9b898c12d8</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[quality]]></category>
            <category><![CDATA[static-analysis]]></category>
            <category><![CDATA[detekt]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Alfredo Cerezo Luna]]></dc:creator>
            <pubDate>Wed, 05 Sep 2018 20:18:40 GMT</pubDate>
            <atom:updated>2018-09-05T20:41:53.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*INP4iVQ4ikst8VvvMQjg2A.png" /></figure><p>Back in 2017, I wrote about how to configure Detekt for an Android multi-module project:</p><p><a href="https://medium.com/@acerezoluna/static-code-analysis-tools-for-kotlin-in-android-fa072125fd50">Static Code Analysis Tools for Kotlin in Android</a></p><p>And now is time to update this article with the latest state of this static analysis tool. <br>This process is much easier now, and it only takes a few steps to have it checking your Kotlin modules selectively.</p><h4>First: Add the <em>classpath</em> dependency to your existing dependencies in your root build.gradle.</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c04d7fc46039f7dcb10f242ecb721e6e/href">https://medium.com/media/c04d7fc46039f7dcb10f242ecb721e6e/href</a></iframe><h4>Second: Create your Detekt rules configuration file.</h4><p>In this file you can specify which rules should Detekt follow to check your code.<br>This file is very easy to create, just take a look at the official documentation and follow the instructions.</p><p><a href="https://arturbosch.github.io/detekt/configurations.html">Detekt Configuration File | A static code analyzer for Kotlin</a></p><p>You can name this file <em>detekt-ruleset.yml</em>, and you can put it in the project root path, or create a quality folder just to store it with other configuration files for other tools.</p><h4>Third: Create your Detekt configuration file.</h4><p>You can call it <em>detekt.gradle</em> , and it would be better if you put this file also in the same location that you put the rules file before.</p><p>Keep in mind that all values can be different from the values in the snippet below since it depends on the folders structure of your project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4befdef67d82b69da4c7ccb4c3da97f6/href">https://medium.com/media/4befdef67d82b69da4c7ccb4c3da97f6/href</a></iframe><p>The field <em>input</em> indicates the directory where your Kotlin files reside.<br>The field <em>config</em> indicates the location of the rules files from the second step.<br>The filed <em>filters</em> indicate which files should be skipped during the scan, for instance, test files.<br>The field <em>output</em> indicates where we want to store the report file that contains all the issues that Detekt founds.<br>The field <em>parallel</em> is an optimisation for performance if your project contains more than 200 files.</p><blockquote>Don’t forget the first line: apply plugin: “io.gitlab.arturbosch.detekt”</blockquote><h4>Last: apply the plugin to (every) kotlin module.</h4><p>You just need to add</p><pre>apply from: &#39;../quality/detekt.gradle&#39;</pre><p>at the top of your module’s<em> build.gradle</em>, keep in mind that the path might vary depending on where you define your configuration file during the second or third step.</p><p>Repeat this step in all modules that we want to get checked by the tool.</p><h4>Done!</h4><p>Just run this in your terminal:</p><pre>./gradlew detektCheck</pre><p>Thanks for reading and happy testing!</p><h4>References</h4><p>Detekt — <a href="https://arturbosch.github.io/detekt/index.html">https://arturbosch.github.io/detekt/index.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f9b898c12d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 3b: RecyclerView from zero to hero.]]></title>
            <link>https://medium.com/@acerezoluna/part-3b-recyclerview-from-zero-to-hero-ce4442ebeede?source=rss-771f79a5b93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce4442ebeede</guid>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[custom]]></category>
            <category><![CDATA[swipe]]></category>
            <category><![CDATA[background]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alfredo Cerezo Luna]]></dc:creator>
            <pubDate>Tue, 27 Feb 2018 20:27:57 GMT</pubDate>
            <atom:updated>2018-02-28T07:39:08.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LkAZzpNjX-wWpCKKdS-EiQ.png" /></figure><p>Let’s make it shine: expanding circle background effect!</p><p>What you will find here:</p><p>During the last three posts: <a href="https://medium.com/@acerezoluna/part-1-recyclerview-from-zero-to-hero-4e1bb0b087fd"><em>Part 1- First things first: implementing a basic RecyclerView</em></a><em> , </em><a href="https://medium.com/@acerezoluna/part-2-recyclerview-from-zero-to-hero-d44f345e93ed"><em>Part 2 — Giving it functionalities: swipe and drag &amp; drop</em></a><em> and </em><a href="https://medium.com/@acerezoluna/part-3-recyclerview-from-zero-to-hero-397b7996280"><em>Part 3-</em>The devil is in the details: customise your items’ background</a>, we learned how to implement a RecyclerView from zero, we learned how to add swipe gestures, and how to add a custom background to each element when it’s being swiped. Now, let’s make it shine! we are going to add an expanding circle animation to show us the progress of our gesture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*aQ3DqmYMRLXCIRr37VZ5GQ.gif" /><figcaption>Swipe circle effect</figcaption></figure><p>Maybe you want to take a look to the previous articles to get some context, more precisely to the <a href="https://medium.com/@acerezoluna/part-3-recyclerview-from-zero-to-hero-397b7996280">Part 3</a>.</p><h3>The idea:</h3><p>The idea here is to paint a circle as a background instead of a rectangle, to do that, we are going to modify the class SwipeBackgroundHelper from the last post, now the method drawBackground():RectF should looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5681c12aa8a629e65a7dadfbe03859da/href">https://medium.com/media/5681c12aa8a629e65a7dadfbe03859da/href</a></iframe><p>This code basically paints a circle of center cx and cy, these values are going to be calculated using the position of the item being swiped, and represented using a new Paint in our class:</p><pre>private var circlePaint: Paint? = Paint(Paint.<em>ANTI_ALIAS_FLAG</em>).<em>apply </em><strong>{<br>    </strong><em>color </em>= Color.<em>RED<br></em><strong>}</strong></pre><blockquote>Remember that coordinates in Android goes from up to button, and the coordinates of the item’s background are defined by a rectangle in absolute values.</blockquote><p>The Y coordinate that specifies the center position of the circle will be the top position of the item’s background plus half of its height (this is the center of the rectangle that defines the background):</p><p>val cy = backgroundRectangle.top + viewItem.height / 2</p><p>and it’s X coordinate will be the left side position of the item’s background plus a fixed offset, this offset is going to add some separation between the center of the circle and the edge of the background that we are painting:</p><p>val cx = backgroundRectangle.left + leftOffset</p><p>to paint it’s radius we will do it according to the distance swiped</p><pre>val circleRadius = (Math.abs(dX / viewItem.<em>width</em>) - threshold) * viewItem.<em>width </em>* CIRCLE_ACCELERATION</pre><p>This value (Math.abs(dX / viewItem.width) will oscillate between 0 and 1 and viewItem.width * CIRCLE_ACCELERATION will represent the total length, we multiple it by CIRCLE_ACCELERATION to make the circle bigger, the size will differ but the time frame of the gesture will be the same, so that it will grow faster or slower depending on this value, play with it!</p><p>So far so good, but you might notice that we are painting too much stuff that it’s covered by other views, we just want to see a portion of the circle, so no need to paint it entirely, to fix that let’s going to “clip” the circle inside the rectangle that defines our background, we get this rectangle using the method getBackGroundRectangle()from the previous post, to clip means to ‘cut’ using the bounds provided and keeping what rests inside.</p><pre>canvas.clipRect(backgroundRectangle)</pre><p>And that’s it! Now just paint the circle:</p><pre>canvas.drawCircle(cx, cy, circleRadius, circlePaint)</pre><p>And you should have something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*aQ3DqmYMRLXCIRr37VZ5GQ.gif" /><figcaption>Swipe circle effect</figcaption></figure><h3>Summary</h3><p>This post was very small, but very significant, we saw how just by adding a small animation we get a more responsive UI.<br>Specially thanks to <a href="https://medium.com/u/22c02a30ae04">Nick Butcher</a>, he implemented this effect before me and shared his work, giving me the opportunity to adapt it to the needs of this example.</p><p>So this is the end, thank you for reading this, hopefully now you are a little bit better thanks to these posts, and that’s enough for me.</p><p>Happy coding!</p><h3>Code:</h3><p><a href="https://github.com/Jachu5/recycler/blob/master/app/src/main/java/com/unchained/itemtouchexample/SwipeBackgroundHelper.kt">https://github.com/Jachu5/recycler/blob/master/app/src/main/java/com/unchained/itemtouchexample/SwipeBackgroundHelper.kt</a></p><h3>Reference:</h3><p>Plaid Code: <a href="https://github.com/nickbutcher/plaid/blob/master/app/src/main/java/io/plaidapp/ui/recyclerview/FilterTouchHelperCallback.kt">https://github.com/nickbutcher/plaid/blob/master/app/src/main/java/io/plaidapp/ui/recyclerview/FilterTouchHelperCallback.kt</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce4442ebeede" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 3: RecyclerView from zero to hero]]></title>
            <link>https://medium.com/@acerezoluna/part-3-recyclerview-from-zero-to-hero-397b7996280?source=rss-771f79a5b93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/397b7996280</guid>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[custom]]></category>
            <category><![CDATA[background]]></category>
            <category><![CDATA[swipe]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alfredo Cerezo Luna]]></dc:creator>
            <pubDate>Tue, 27 Feb 2018 20:22:12 GMT</pubDate>
            <atom:updated>2018-02-27T20:29:33.017Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*PQdA60anfUv4gvNCxRAWnQ.png" /></figure><p>The devil is in the details: customise your items’ background.</p><p>What you will find here:</p><p>In the last two post:<a href="https://medium.com/@acerezoluna/part-1-recyclerview-from-zero-to-hero-4e1bb0b087fd"> <em>Part 1- First things first: implementing a basic RecyclerView</em></a><em> and </em><a href="https://medium.com/@acerezoluna/part-2-recyclerview-from-zero-to-hero-d44f345e93ed"><em>Part 2 — Giving it functionalities: swipe and drag &amp; drop</em></a> we covered how to implement a basic RecyclerView and how we can add swipe and drag &amp; drop, so now is turn to make our RecyclerView a little bit better.<br>We are going to learn how to paint a nice background and an icon when we swipe an item, this way we give to the user a hint that something is about to happen while he/she swipes an item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*EiG6EGfZRbJJZT9IwUTjLQ.png" /></figure><h3>The basics</h3><p>Remember our ItemTouchHelper.Callback() implementation from the previous post? In case you don’t:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6834a37f8daba9a26ac749eb05ba9a60/href">https://medium.com/media/6834a37f8daba9a26ac749eb05ba9a60/href</a></iframe><p>The ItemTouchHelper.Callback() does lots of things, and one of them is to control how the system paints the view that we are interacting with, the following method does that job:</p><p>public void onChildDraw(Canvas c, RecyclerView recyclerView,ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive)</p><p>By default, the ItemTouchHelper moves the item applying a translation leaving an empty background, but if we override this method we can customize this behaviour and paint a custom one using the Canvas c, we don’t need to worry about anything else, the method itself is going to take care of how to paint the background according to the Android version.</p><p>The method onChildDraw is called iteratively by the RecyclerView updating the dx and dy values, which specify the amount of space the ItemView has been moved.</p><p>So let’s do it!</p><p>First of all I am going to assume that you got a basic idea on how a Canvas works, if you don’t, don’t panic, we are going to make it easy (at least for painting something basic), once you finish this post you will just need to care about which icon do you want to draw and the color for your background.</p><p>We are going to create a utility class that is going to all this work painting a background following the next steps:</p><ul><li>Getting the resources, namely: background color and icon.</li><li>Drawing the background.</li><li>Drawing the icon.</li></ul><h4>Getting the resources</h4><p>This step is optional, we can ignore it and hardcode everything, or we can follow a more generic approach in which we define externally the id of the resources, this way we can reuse this code in other projects, and even better, we are going to decouple our drawing logic from our resource creation logic giving us the chance to extend it in a future.</p><p>For this purpose let’s encapsulate our resources inside a private class that will help us to keep this information along the drawing process:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35d06dda99893bc336223d0c29a8dbcc/href">https://medium.com/media/35d06dda99893bc336223d0c29a8dbcc/href</a></iframe><p>And now lets define a couple of helper methods to create objects of this type</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd43a77da8407e7455fe584ddfa5ad88/href">https://medium.com/media/bd43a77da8407e7455fe584ddfa5ad88/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/596db755c5f370c1a416cb2bc3f7030f/href">https://medium.com/media/596db755c5f370c1a416cb2bc3f7030f/href</a></iframe><p>We want to provide two kind of feedback to the users: one to show that an element has reached the threshold distance and the action is triggered, and another one to show that the distance is not enough yet.</p><p>To know when the item has reached the threshold distance we use this helper function that takes the width of the view and the distance already swiped by the item, and checks if this is bigger or smaller than a threshold value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87ee4f20307e9d0fbfd29e76c4de4c0f/href">https://medium.com/media/87ee4f20307e9d0fbfd29e76c4de4c0f/href</a></iframe><p>The isolation of this logic is important, this way we can change this condition by something more complex, and more important, we can reuse this logic somewhere else in de code.</p><h4>Drawing the background</h4><p>To do this we are going to use a Paint, a Paint basically is a container that holds the style and color to be used to draw inside a canvas.</p><p>We want to paint a rectangle that fills the empty space left by the swiped item, and this rectangle is going to be specified using a RectF, another Android class that defines a geometric shape specifying its bounds.</p><p>Once we have created both objects we only need to tell the canvas to paint in itself a RectF following the rules specified by the Paint</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/278529d1a38fcf87fa0ad20b9928caec/href">https://medium.com/media/278529d1a38fcf87fa0ad20b9928caec/href</a></iframe><blockquote>In Android the coordinate system for graphics has its origin in the (0,0), this origin is located in the upper left corner, therefore if we move the item to the bottom of the screen we are moving along the positive Y-axe, and if we move the item to the right, we are moving along the positive X-axe</blockquote><p>Let’s analyse deeper how we define the RectF: as you can see, the upper and bottom bounds are always the same, they correspond with the bounds of the view that we are swiping.</p><p>The right bound correspond with the right bound of the swiped view (we are swiping to the left), and the left bound corresponds also with the right bound of the swiped view, so that we have an invisible rectangle of with 0 at the beginning. But if we modify the view swiping it, it’s right bound is going to be moved also, and the rectangle we are painting grows as long as we keep on doing the gesture, since the left bound of the background stays with it, leaving an empty space where the background it’s going to be painted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*sfsZkLWDiVk4iam9VrbiEg.jpeg" /></figure><h4>Drawing the icon</h4><p>This is the most delicate part because we need to locate the icon inside the space occupied by the background painted in the previous step.</p><p>To paint a Drawable over a canvas we need to define the container rectangle, in this case another Rect, the Drawable will be deformed to fill the space defined by this Rect, so we need to be very careful to not change the original shape an ratio of the raw icon.<br>Our goal is to paint and move this icon while we swipe the recyclerview item, so lets define and modify these 4 bounds of this Rect to achieve that.</p><p><strong>Top and bottom: </strong>we want to allocate our icon in the middle of the vertical space left by the swiped item, so we define a bottom and top margin, so let’s calculate how much space we need to leave on the top and bottom.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67e4d21f493bbc7652635565d611c232/href">https://medium.com/media/67e4d21f493bbc7652635565d611c232/href</a></iframe><p><strong>Left</strong>: the left bound of the Rect icon’s container will move with the view being swiped, this way we give the perception to the user that the icon is being animated, how can we know this value? easy, we got the value dx(negative) which measures the amount of space the view has been moved and we also have the position of the item’s right bound (remember that we are just swiping to the left).</p><p><strong>Right:</strong> intuitively you may think that this bound is somehow related with the right bound of the item, but nothing further from the reality, the truth is that this value is going to be the previously calculated left bound, plus the width of the icon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*a6OH7wCOZdnwsQffGAesQA.jpeg" /></figure><p>Resulting in this code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b2f437de7e324f0b240ff9ccbcc8d5f/href">https://medium.com/media/7b2f437de7e324f0b240ff9ccbcc8d5f/href</a></iframe><p>And now we just tell the icon to draw itself over the canvas inside the Rectthat we just defined icon.draw(canvas)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc3041cb2a8cccccedc8b8246c24247c/href">https://medium.com/media/fc3041cb2a8cccccedc8b8246c24247c/href</a></iframe><h4>Everything together</h4><p>So now to draw our icon we just need to put everything together in the following way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cbb4ccb40395f5b3182f353e6e6e72d/href">https://medium.com/media/5cbb4ccb40395f5b3182f353e6e6e72d/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2383b6bf2d3e443725d6f28422f09d2/href">https://medium.com/media/d2383b6bf2d3e443725d6f28422f09d2/href</a></iframe><p>An call this last method from our ItemTouchHelperCallback, more precisely from the onChildDraw() method</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/918f782225753508013783c1d6e25d9c/href">https://medium.com/media/918f782225753508013783c1d6e25d9c/href</a></iframe><p>And this is it! We have isolated all the complexity in just one method call!</p><pre>SwipeBackgroundHelper.paintDrawCommandToStart(canvas, viewItem, R.drawable.<em>ic_trash</em>, dX)</pre><p>Now we should have something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*QQtVNAgYqB4dPBWmrfPX7w.gif" /><figcaption>Background and icon</figcaption></figure><h3>Summary</h3><p>Plenty of things on this post, we modified our code to paint a background while we swipe an item in a way that its color changes when the action its triggered, and we also added a nice icon which moves together with the item showing to our users which action are they triggering with the action.</p><p>To do this, we splited everything in three phases: one to get all the resources, one to paint the background and another one to paint the icon.</p><h3>Continue reading</h3><p><a href="https://medium.com/@acerezoluna/part-3b-recyclerview-from-zero-to-hero-ce4442ebeede">Part 3b: RecyclerView from zero to hero — Let’s make it shine: expanding circle background effect!</a></p><h3>Code</h3><p><a href="https://github.com/Jachu5/recycler">Jachu5/recycler</a></p><p>Thanks for reading! Any comment or feedback is welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=397b7996280" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2: RecyclerView from zero to hero]]></title>
            <link>https://medium.com/@acerezoluna/part-2-recyclerview-from-zero-to-hero-d44f345e93ed?source=rss-771f79a5b93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d44f345e93ed</guid>
            <category><![CDATA[drag-and-drop]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[swipe]]></category>
            <category><![CDATA[custom]]></category>
            <dc:creator><![CDATA[Alfredo Cerezo Luna]]></dc:creator>
            <pubDate>Tue, 27 Feb 2018 20:07:22 GMT</pubDate>
            <atom:updated>2018-02-27T20:23:55.602Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*4SIlk_owOCVkKS2QnJGOpA.png" /></figure><p><em>Giving it functionalities: swipe and drag &amp; drop.</em></p><p>Thanks for staying with me!</p><p>What you will find here:</p><p>Now we are going to explore how we can modify our RecyclerView from Part <a href="https://medium.com/@acerezoluna/part-1-recyclerview-from-zero-to-hero-4e1bb0b087fd">1 — First things first: implement a basic RecyclerView</a>, to support swipe and drag &amp; drop actions. To do that, we are going to use ItemTouchHelper, a utility class provided by Android which makes everything really easy.</p><h3>ItemTouchHelper in deep</h3><p>Lots of things are going on in this class, so let’s try to rip it and take a more detailed view of it.</p><p>As we saw in the previous post, a <em>ViewHolder</em> is going to present our information in each row of the list (items), if we want to interact with the elements within our list we need to play with it, and this is the purpose of the ItemTouchHelper class: to give us the tools and methods that make everything easier.</p><p>This class contains several things: methods provided by itself and, probably the most important part, a set of callbacks that serves as a contract between this class and our application.</p><p>Let’s start with the former:</p><p>ItemTouchHelper.Callback { ... }</p><p>We need to implement this interface and override some methods to enable/disable the actions that our users can perform, but also to receive some callbacks calls as responses of some actions.</p><p>First interesting method:</p><p>public abstract int getMovementFlags(RecyclerView recyclerView, ViewHolder viewHolder);</p><p>Basically we have to tell the ItemTouchHelper if an item (ViewHolder) is swappable or draggable, to do that we will define some flags that the ItemTouchHelper will check, but these flags mean more, they also indicate the directions in which our items can be swiped (right or left) or moved (up or down), and we can even specify the direction in which an item can be moved when starting the action, and in which directions can be moved while performing the action. For instance: an item could be only swiped to the right, but once I start swiping, I can move it to the right or to the left.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d529ccad69810930d8ffc9b0fc953e66/href">https://medium.com/media/d529ccad69810930d8ffc9b0fc953e66/href</a></iframe><p>And thanks to this static method, provided also by the Callback, this process is very simple and easy:</p><p>public abstract int getMovementFlags(RecyclerView recyclerView, ViewHolder viewHolder);</p><p>Next interesting method inside the <em>Callback</em>:</p><p>public boolean canDropOver(RecyclerView recyclerView, ViewHolder current, ViewHolder target);</p><p>If you are just using only one type of ViewHolder (our example), most probably you don’t care about this, but the purpose of this method is to decide whether we can drop an item over another or we can not, for instance, if we don’t want to swipe positions between a regular item and a header inside our list. The easiest way to achieve that is checking in this method if both ViewHolders are of the same type (using instanceOf() is a good option in this case).</p><p>Another important method we need to implement to perform drag &amp; drop:</p><p>public abstract boolean onMove(RecyclerView recyclerView, ViewHolder viewHolder, ViewHolder target);</p><p>This method is called by the ItemTouchHelper when it wants to move the item we are dragging from one position to a new one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1a6d25600d2e805cbf24aba28da3bc5/href">https://medium.com/media/e1a6d25600d2e805cbf24aba28da3bc5/href</a></iframe><p>In this example, the Callback delegates into our adapter how to handle these actions, but we will talk about this later.</p><p>And we have a similar method to announce that one item has been swiped:</p><p>public abstract void onSwiped(ViewHolder viewHolder, int direction)</p><p>Here you got the implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f44e94c470033c51b52b53fe10966a10/href">https://medium.com/media/f44e94c470033c51b52b53fe10966a10/href</a></iframe><p>That pretty much covers all the methods we need, but how theItemTouchHelper communicates with the adapter (our source of data for the RecyclerView)? We don’t know if the adapter is going to be always the same so it’s better to keep them decoupled, let’s create an interface for this purpose, we just need two methods: one for onMove() and one for onSwiped() :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*5pb11an9ZpJlUv_IFX2PUw.png" /></figure><p>and this is the interface definition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/070e2d6f89504b055cd8165556c97ba5/href">https://medium.com/media/070e2d6f89504b055cd8165556c97ba5/href</a></iframe><p>Here you can find the implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6834a37f8daba9a26ac749eb05ba9a60/href">https://medium.com/media/6834a37f8daba9a26ac749eb05ba9a60/href</a></iframe><p>As I mentioned before in this example, the adapter is going to be the one who handles this changes in the data, so it needs to implement this interface. Resulting in the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a468c70c5971ad0838c863ec60ecdd6/href">https://medium.com/media/2a468c70c5971ad0838c863ec60ecdd6/href</a></iframe><p>And now we need to put everything together:</p><ul><li>Create the callback.</li><li>Create the ItemTouchHelper from the callback.</li><li>Attach the RecyclerView to it.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b88ab53118fe20da7bce6f9cd988c67/href">https://medium.com/media/7b88ab53118fe20da7bce6f9cd988c67/href</a></iframe><p>And this is how it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*nP_XexYT0QnS_SK_IbgD2A.gif" /></figure><h3>Summary</h3><p>We covered how to extend the functionalities of our RecyclerView, by adding swipe and drag &amp; drop using ItemTouchHelper. To do that we implemented an ItemTouchHelper.Callback interface and created a helper interface that our adapter implements in order to communicate with it.</p><p>In the last post, we will cover how to draw a background when we swipe an element to give some meaning to our actions.</p><h3>Continue reading</h3><p><a href="https://medium.com/@acerezoluna/part-3-recyclerview-from-zero-to-hero-397b7996280"><em>Part 3 — Painting a background while swiping.</em></a></p><h3>Code</h3><p><a href="https://github.com/Jachu5/recycler">Jachu5/recycler</a></p><p><em>Thanks to </em><a href="https://twitter.com/aconsuegra"><strong><em>@</em></strong><em>aconsuegr</em></a>a <em>for reviewing this post.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d44f345e93ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1: RecyclerView from zero to hero]]></title>
            <link>https://medium.com/@acerezoluna/part-1-recyclerview-from-zero-to-hero-4e1bb0b087fd?source=rss-771f79a5b93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e1bb0b087fd</guid>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[custom]]></category>
            <category><![CDATA[swipe]]></category>
            <category><![CDATA[drag-and-drop]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alfredo Cerezo Luna]]></dc:creator>
            <pubDate>Tue, 27 Feb 2018 19:58:06 GMT</pubDate>
            <atom:updated>2018-02-27T20:28:45.355Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*2Ay8_fLZK9ELg8i58-CLDw.png" /></figure><p>By the end of this series you will have a RecyclerView with drag &amp; drop and swipe with custom background, that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*OUmygHVUnT7eyLNt2xFxJg.gif" /><figcaption>RecyclerView with swipe and drag&amp;drop</figcaption></figure><p>During 4 posts I will try to show you how to implement a basic RecyclerView that allows you to perform <strong>drag &amp; drop/swipe</strong> with custom backgrounds, and during the former case I will try to show you how to animate anything here.</p><p><em>Part 1- First things first: implementing a basic RecyclerView(easy peasy).</em></p><p><a href="https://medium.com/@acerezoluna/part-2-recyclerview-from-zero-to-hero-d44f345e93ed"><em>Part 2 — Giving it functionalities: swipe and drag &amp; drop.</em></a></p><p><a href="https://medium.com/@acerezoluna/part-3-recyclerview-from-zero-to-hero-397b7996280"><em>Part 3 — Painting a background while swiping.</em></a></p><p><a href="https://medium.com/@acerezoluna/part-3b-recyclerview-from-zero-to-hero-ce4442ebeede"><em>Part 3b: RecyclerView from zero to hero — Let’s make it shine: expanding circle background effect</em></a></p><p>If you have some background knowledge with RecyclerView you may want to jump to <a href="https://medium.com/p/d44f345e93ed/edit">part 2</a> directly.</p><h3>Part 1 — First things first: implementing a basic RecyclerView</h3><p>First things first: implementing a basic RecyclerView (easy-peasy).</p><p>Nothing especial here, we start with our favorite Activity, our MainActivity, and we declare the RecyclerView by adding it to the layout.xml.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed12be4c2978c9aa99351dfa21864c62/href">https://medium.com/media/ed12be4c2978c9aa99351dfa21864c62/href</a></iframe><p>Most probably you are familiar with RecyclerViews, so the term ViewHolder does not scary you, but just in case, a ViewHolder is an Android pattern to reuse views and avoid the extra cost of inflating them and calling findViewById()every time an item shows up in the screen.</p><p>Nowadays, thanks to the RecyclerView, the system will handle all this complexity for us, so we only need to worry about the type of ViewHolder we are creating and how we update the data within it.</p><p>How RecyclerView works, and how it handles this recycling process is out of the scope of this post but you can find a lot of information in the internet.</p><p>So as I mentioned before, we have to define a ViewHolder, that will hold the reference to our views, inside each item of the list, we can have as many different types of ViewHolders as we want according to the number of different items we want to display, for instance: headers, footer, regular items are different types of items.</p><p>For now let’s define a super simple one, one that only holds a TextView, the ViewHolder also needs to contain a function that maps the new information that may come with each view we want to update inside our item, we typically call this method bind(), but it’s completely up to you.</p><blockquote>If you are using Kotlin extensions, be super careful of where you assign the view reference inside the holder (never inside the binder method call if we are not inside an Activity or Fragment), or you can achieve the opposite of what we are looking for.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77f594c1155bb036e7e8ba7c24437277/href">https://medium.com/media/77f594c1155bb036e7e8ba7c24437277/href</a></iframe><p>And now its turn for the Adapter, this is the component that handles everything, it binds the data from the app with the displayed views, and it also creates and updates the ViewHolders.</p><p>Three methods are important here for the purpuse of this post:</p><p>override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewAdapter.ItemViewHolder</p><p>Called when the RecyclerView needs a new ViewHolder to represent some data of a given type, this ViewHolder will be reused all the time to display new data, to do that, the system just update the inner views inside it. (findViewById() will be called only here, so if your item is composed by a TextView and a ImageView the system will update the information showed by the views, but no the view referenced by itself in the future)</p><p>override fun onBindViewHolder(holder: ItemViewHolder, position: Int)</p><p>This method is called by the RecyclerView to display data in a certain position, basically it updates the content of the view (all the references previously created in onCreateViewHolder). It is called when a view is invalidated or it has a new position that cannot be determined.</p><p>override fun getItemCount(): Int</p><p>This method returns the number of elements that your RecyclerView is displaying, apparently this is not important, it’s only purpose is to return the size of your collection, but if your data gets more complicated, and you want to show headers, footers, etc. you would need to modify this value artificially.</p><p>There are a few methods more that are also important:</p><p>public int getItemViewType(int position) important if ,as it was mentioned before, you want to show extra items out of your data set, like footers or headers. <br>Or public long getItemId(int position) if you want to refresh data and just update those elements that have changed, but both methods are way out of the scope of this post.</p><p>So here we got our adapter</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ba9ca4b3a20749212d1158a7a0b93b1/href">https://medium.com/media/5ba9ca4b3a20749212d1158a7a0b93b1/href</a></iframe><p>You probably notice a couple of thing here that we did not mention before, first:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1355003e7851dba6a366a357f71b1a1f/href">https://medium.com/media/1355003e7851dba6a366a357f71b1a1f/href</a></iframe><p>Don’t worry it is just an <em>extension function</em> for the class ViewGroup that allows us to clean up a little bit our code.</p><p>And second:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbc5a4c7f5e0e335aaffefd632421d1a/href">https://medium.com/media/dbc5a4c7f5e0e335aaffefd632421d1a/href</a></iframe><p>Here we define our data set as a member of the adapter , it is important not only to have something to show, but also to know if we can or cannot interact with it, please notice that we are using MutableList because of that, otherwise you may want to use an immutable set in order to avoid the data to be changed.</p><p>So now let’s put everything together in our Activity or Fragment like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72b1d116ad259284e3f5e658e4513799/href">https://medium.com/media/72b1d116ad259284e3f5e658e4513799/href</a></iframe><p>And here we go, we should have now a basic list that allows us to scroll down and up, in the next part I will cover how to add <strong>swipe/drag &amp; drop</strong> to implement rich interaction patterns with our data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*ls_b4ydXHgTHxUAZkXE5Ig.gif" /></figure><h3>Summary</h3><p>We covered how to create a basic RecyclerView, if you want to know more in deep any topic mentioned during the post you can visit:</p><p><a href="https://antonioleiva.com/extension-functions-kotlin/">Antonio Leiva: Extension functions in Kotlin</a></p><p><a href="https://proandroiddev.com/the-costs-of-kotlin-android-extensions-6809e2b32b13">Miguel Beltran: The costs of Kotlin Android Extensions</a></p><p><a href="https://www.youtube.com/watch?v=KhLVD6iiZQs">Yigit Boyar: Pro RecyclerView</a></p><h3>Continue reading</h3><p><a href="https://medium.com/@acerezoluna/part-2-recyclerview-from-zero-to-hero-d44f345e93ed"><em>Part 2 — Giving it functionalities: swipe and drag &amp; drop.</em></a></p><h3>Code</h3><p><a href="https://github.com/Jachu5/recycler">Jachu5/recycler</a></p><p><em>Thanks to </em><a href="https://twitter.com/aconsuegra"><strong><em>@</em></strong><em>aconsuegr</em></a>a <em>for reviewing this post.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e1bb0b087fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Static Code Analysis Tools for Kotlin in Android]]></title>
            <link>https://medium.com/@acerezoluna/static-code-analysis-tools-for-kotlin-in-android-fa072125fd50?source=rss-771f79a5b93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa072125fd50</guid>
            <category><![CDATA[detekt]]></category>
            <category><![CDATA[static-analisys]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Alfredo Cerezo Luna]]></dc:creator>
            <pubDate>Sat, 28 Oct 2017 16:53:15 GMT</pubDate>
            <atom:updated>2018-09-05T20:22:23.525Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article we will learn how to include a static analysis tool (Detekt) for a multi module Android Kotlin project, we also are going to learn how we can set it up to apply a set of rules to check the style, code smells, etc.</p><blockquote>Note: this article is outdated, please check my last post about how to configure the last Detekt version.</blockquote><p><a href="https://medium.com/@acerezoluna/detekt-in-2018-5f9b898c12d8">Detekt in 2018</a></p><h4>Alternatives</h4><p>Probably you are familiar with some kind of static analysis tool, basically these tools check our code without actually executing it, they look for code smells, possible memory leaks, they measure the cohesion and dependencies between classes or identify style incoherencies.<br>This labor is critical to maintain a good foundation in our code, and to keep the whole team in the same page.</p><p>For Java there are plenty: pmd, findbugs, checkstyle, SonarQube, just to name a few, but in Kotlin the choice is not that wide, so far I have been able to find two meaningfully options: <strong>Detekt</strong> and <strong>Ktlint</strong>, I personally don’t like Ktlint since its rules cannot be modified and the existing Gradle plugins are not easy to integrate, on the other hand, <strong>Detekt</strong>, works pretty fine, its plugin is still a bit too new, but its a promising option.</p><h4>Detekt</h4><p>Detekt gives us several interesting metrics:<br>- Code smells.<br>- Complexity report.<br>- Code style check.</p><p>The tool writes a report using the console, which looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HyYzJnifuL8eshk6BkoeXQ.png" /><figcaption>Detekt console output</figcaption></figure><p>But also it can beconfigured to write the output in different files: plain text or xml.</p><p>Detekt performs its analysis based on a set of rules we can configure in a .yml file, for instance we can define the error threshold to break the build, enable or disable rules, enable or disable auto editing options, etc.</p><p>This configuration is done by using a closure that we can define in an external file, which looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c9583c3c75b8988026766655cf866c5/href">https://medium.com/media/3c9583c3c75b8988026766655cf866c5/href</a></iframe><p>It can be configured to work different for each submodule inside a project using Gradle profiles, which give us the opportunity to apply different set of rules to a different submodules.</p><p>To know more about the properties that we can define please visit its GitHub page (you can find it in references).</p><p>In Android its integration is not the most desirable so far. What I am going to show is the best I was able to do in a multi module project, any other alternative I tried gave me different sort of problems, so here we are, if you find out a different way, please leave a comment.</p><h4>Project Implementation.</h4><p>First in the project.build level you have to add:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75dcf9e51e45df04a71b354d60c093cb/href">https://medium.com/media/75dcf9e51e45df04a71b354d60c093cb/href</a></iframe><p>But this will apply the check in all modules, and we don’t want this. We want to select in which modules we want to run the check. The standard way to go in this case would be to add `<em>apply false</em>` which disable this behaviour, and later on selectively choose in which modules we want to apply the plugin, but this does not work properly with Detekt in Android yet, so we have to manually add the plugin to each build.gradle in each module, it’s not pretty, I know.</p><blockquote>plugins is an experimental feature, so for example we cannot extract the version into an external file :(</blockquote><p>Now we want to load the configuration for Detekt inside each module, as we mentioned before we use a closure for this purpose, and we can write it directly inside the build.gradle or extract it into a separate file and reference it inside de build.gradle in the following way:</p><pre>apply from: ‘../detekt.gradle’</pre><p>Remember, inside this file we must include the closure.</p><p>And now, to run the tool just type :</p><pre>./gradlew detektCheck</pre><p>The console will show you a report with several metrics.</p><p>Happy checking :).</p><h4>References</h4><p>Detekt — <a href="https://github.com/arturbosch/detekt#gradleandroid">https://github.com/arturbosch/detekt#gradleandroid</a><br>Klint - <a href="https://github.com/shyiko/ktlint">https://github.com/shyiko/ktlint</a></p><p><em>Thanks to </em><a href="https://twitter.com/aconsuegra"><strong><em>@</em></strong><em>aconsuegr</em></a>a <em>for reviewing this post.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa072125fd50" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>