<?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 Martin Sumera on Medium]]></title>
        <description><![CDATA[Stories by Martin Sumera on Medium]]></description>
        <link>https://medium.com/@sumera.martin?source=rss-2c37b2ce78c4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LfPYMpgc2n7kMxAMENaOXA.jpeg</url>
            <title>Stories by Martin Sumera on Medium</title>
            <link>https://medium.com/@sumera.martin?source=rss-2c37b2ce78c4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 11:27:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sumera.martin/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[Tricky refactoring of Jetpack Compose code — be careful with side effects]]></title>
            <link>https://medium.com/@sumera.martin/tricky-refactoring-of-jetpack-compose-code-be-careful-with-side-effects-13768275b3db?source=rss-2c37b2ce78c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/13768275b3db</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Martin Sumera]]></dc:creator>
            <pubDate>Wed, 21 Jul 2021 07:32:55 GMT</pubDate>
            <atom:updated>2021-07-21T07:36:13.120Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CKhwR9_F39EtOaz6SeCV0w.png" /></figure><p><strong>Jetpack Compose code is relatively easy to understand most of the time. But as in every other technology, the more you are trying to achieve something complex, the more you need to know about some internals and more advanced concepts. In this article, I will show you an example of how simple refactoring can lead to unexpected issues caused by side effects.</strong></p><h3>Setup</h3><p>Let’s say that we have the composable code with the following behavior:</p><ul><li>It allows the user to insert data into the <em>TextField</em></li><li>It shows a snackbar with an indefinite duration. When the snackbar is dismissed, then it does some action with data inserted into <em>TextField</em>.</li></ul><p>It is nothing difficult to implement. Even though this is quite an unordinary behavior from the UX perspective, it will demonstrate our problem nicely.</p><p>Let’s say that this is a section of our code in which we are interested:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e563d891e3844406040addae27bf68a/href">https://medium.com/media/5e563d891e3844406040addae27bf68a/href</a></iframe><p>The composable is quite simple. But let’s go over it to be clear about the functionality:</p><ol><li>Creates and remembers <em>SnackbarHostState</em> class responsible for showing and hiding the snackbar.</li><li>Creates and remembers <em>text</em> state that holds the data from the <em>TextField.</em></li><li>Creates side-effect via <em>LaunchedEffect</em> that runs suspend functions in the scope of a composable. It uses <em>Unit</em> value as a parameter. It means that it will be started only once when the first composition of the parent composable is executed.</li><li>Shows a snackbar via<em> </em>suspended function and stops the given block’s execution until the snackbar is dismissed. Since the snackbar has an indefinite duration, it can be dismissed only via user action.</li><li>When the snackbar is dismissed, we perform some action with the text state.</li><li>The rest of the code, which is not important right now, is responsible for changing the text state.</li></ol><p>The code is quite simple and works as we wanted. Let’s say that this is our result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*O79wVqP1B46rBncYHfTVxw.gif" /><figcaption>Original solution with correct behavior</figcaption></figure><p>Everything works as intended. The user is able to insert some data, and when the snackbar is dismissed, these data are used within the <em>LaunchedEffect</em> and presented on the screen.</p><h3><strong>Let’s start with refactoring</strong></h3><p>Let’s say that our new feature is finished. The last thing that we want to do is to perform a small refactoring of the code. In order to get more reusable code, we decide to move the <em>LaunchedEffect</em> code into a standalone composable function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efece4224c2744b7a0170ca94984428f/href">https://medium.com/media/efece4224c2744b7a0170ca94984428f/href</a></iframe><p>All we did was copy-paste the code from the <em>LaunchedEffect</em> into a new composable function with <em>state</em> and <em>text</em> as arguments. Now we replace the original code with our new function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2006b004e1fe974f1ac5684a3dd5975a/href">https://medium.com/media/2006b004e1fe974f1ac5684a3dd5975a/href</a></iframe><p>At first glance, this is a very simple refactoring. It’s just a matter of moving code from one function to another. What could go wrong? Let’s test our code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*LTxYOnZAYwKk0pEct0q1JQ.gif" /><figcaption>Refactored solution with incorrect behavior</figcaption></figure><p>Well, our code is not working anymore. The text value captured within the snackbar now holds the initial data instead of changed data. What is going on?</p><h3>The problem</h3><p>Although Jetpack Compose may be seen as some kind of miracle tool that turns functions into UIs, we should not forget that the functions are still functions and the basic principles of Kotlin still apply.</p><p>We need to understand how <em>LaunchedEffect</em> works. The first thing that we need to understand is that <em>LaunchedEffect</em> is code for side effects. The code inside of it is not a composable function, so no recomposition is automatically done. The second thing that we need to understand is that it is launched only when the key parameter is changed and then captures its surrounding variables.</p><p>Our <em>LaunchedEffect</em> is executed only on the first recomposition because the key parameter is constant (<em>Unit</em>). It means that it captures its environment only once. The problem with the refactoring is that we replaced a reference to the remembered <em>MutableState</em> object with a reference to the string parameter. Even though that text state in the original code is also a string but it is a string wrapped with a delegate.</p><p>At first glance, this small refactor may not seem like a significant change, but it is the cause of the invalid result behavior.</p><h3>Solution</h3><p>Now, when we know where the problem is, we need to find a solution. We know that <em>LaunchedEffect</em> is relaunched when the key is changed. Since we are using<em> Unit</em> as a key parameter of the <em>LauchedEffect</em>, it is launched only on the first composition and capturing the reference to the initial data only.</p><p>In order to capture the most recent value of the text parameter, we can replace the <em>Unit</em> with the <em>text </em>parameter in the <em>LaunchedEffect</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8df9717b50593ccf3b1a2af602ad8907/href">https://medium.com/media/8df9717b50593ccf3b1a2af602ad8907/href</a></iframe><p>This way, we will achieve that <em>LaunchedEffect</em> will be launched every time the composable function is executed with a new <em>text</em> parameter. It sounds like something that is going to fix our problem. Let’s test this change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*yn9ETZiEPblN7rLztTQNnw.gif" /><figcaption>Refactored solution with the correct result but with incorrect snackbar behavior</figcaption></figure><p>Well, the result is correct, but we introduced a new problem. <em>LaunchedEffect</em> is executed whenever the <em>text </em>parameter<em> is </em>changed. The previous coroutine scope is then canceled, and a new one is launched. This is causing the effect of showing the new snackbar for every text change.</p><h3>A correct solution</h3><p>Changing the key argument is not a good solution. We do not want to launch a new <em>LaunchedEffect</em> when the text is changed. So what can we try as a next step? Well, we could pass a <em>MutableState</em> object as a parameter. If we would pass the same instance and change only its internal value, then it would work. But if we would pass a different instance, then the problem would still be there. So passing some other kind of object is not a good solution.</p><p>However, the correct solution to this problem is already created in the Compose runtime. The authors of Compose were aware of this problem and created the <em>rememberUpdatedState </em>function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7d63b90bc5a0041966af457d38ffe6f/href">https://medium.com/media/b7d63b90bc5a0041966af457d38ffe6f/href</a></iframe><p>Let’s test the solution with <em>rememberUpdatedState.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*O79wVqP1B46rBncYHfTVxw.gif" /><figcaption>Refactored solution with correct behavior</figcaption></figure><p>The result captured within <em>LaunchedEffect</em> has the correct value, and the snackbar is shown only once. Our refactored solution is finally working correctly again.</p><h4>How <em>rememberUpdatedState </em>works?</h4><p>The <em>rememberUpdatedState</em> may seem mysterious at first glance, but the function is just a wrapper for the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e14e9b5802c7bcba30dcaa4a346ddcc/href">https://medium.com/media/5e14e9b5802c7bcba30dcaa4a346ddcc/href</a></iframe><p>It wraps the parameter with remembered <em>MutableState</em> and updates its value on every recomposition. By doing this, the <em>LaunchedEffect</em> is referencing the same instance of the <em>MutableState</em> object instead of the text parameter. So even after recomposition, the <em>LaunchedEffect</em> still references the correct instance, which changes only its internal value.</p><p><strong>TL;DR</strong><br>Always be careful when using the side effects in Jetpack Compose. Especially be cautious whether parameters used within functions such as <em>SideEffect</em>, <em>LaunchedEffect</em> or <em>DisposableEffect</em>, hold the most recent value. This can be achieved by referencing remembered state (<em>rememberUpdatedState</em>) or passing the value as the key parameter of the side effect function.</p><p>If you are interested in a more detailed implementation of the code used in this article you can see it in <a href="https://gist.github.com/SumeraMartin/ba8003a7b7e3b39f0db25286fe11a8b5">this gist</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13768275b3db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google IO 2021 — overview]]></title>
            <link>https://medium.com/@sumera.martin/google-io-2021-overview-3ff019847217?source=rss-2c37b2ce78c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ff019847217</guid>
            <category><![CDATA[material-you]]></category>
            <category><![CDATA[googleio]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[android-12]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Martin Sumera]]></dc:creator>
            <pubDate>Fri, 21 May 2021 17:34:04 GMT</pubDate>
            <atom:updated>2021-05-21T17:34:32.412Z</atom:updated>
            <content:encoded><![CDATA[<h3>Google IO 2021 — overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKjGf3sMcK7r-lxMjFQ77A.png" /></figure><p><strong>The keynotes from the Google IO developer conference are over, and we are ready to summarize the most important things that we think will shape our work in the future.</strong></p><p>Since the conference was canceled last year, we were looking forward to this year even more. Due to the pandemic situation, some things were changed. The big amphitheater used for the keynote was replaced with the small stage inside the Google campus, and most of the talks were streamed online from the speaker’s homes. But these changes didn’t affect the event. The announcements were still exciting. So let’s take a look at the things that catch our attention the most.</p><h3>Android 12</h3><p>It’s not a big surprise that the new public beta version of the Android system was announced. However, we can finally see the big picture of all expected and unexpected features. The final version of the system should be available in the Q3 of this year and focuses primarily on the new design system and the privacy improvements. The system should also provide better personalization options for the users, which allows them to change theming of the application. It can be changed based on their preferences or recommendations from the system. The system is able to derive these values from the used wallpaper, for example. Except for all these things, the system should have a better battery life, provide a new way to create more interactive and visually appealing widgets, better integration with Google Assistant, and much more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ek7Tca3J265MVz5p.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z77gGnTGvWSZpqJP.jpeg" /><figcaption>Android 12 with the personalization options</figcaption></figure><h3>Material You</h3><p>The latest redesign is coming at the time when the current Material Theme is in use since 2014 and has been mostly unchanged since then. Material You is a colorful redesign with a lot of personalization options focused on “You”. It should add flexibility to customize your own color swatches, contrast, element sizes, and line widths. The updated components combine the newer interface elements from the current Material Design standard but re-introduce them in the more fresh and more colorful versions. Material You is also aiming at animations to provide more natural and intuitive interactions. The new design language is not only for the applications. It is going to expand to other platforms as well, including watches, smart displays, the web, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pKjJ7e8eSoD9V3-5-G2-lw.png" /><figcaption>Material You on Android devices</figcaption></figure><h3>Wear</h3><p>Google was neglecting the Wear OS for a few years. The system was not getting enough attention, and the last major update is from 2018. The popularity of the platform was lagging behind other competitors such as Samsung’s Tizen or Apple Watch. But Google is now reviving this project and announced a collaboration with Samsung to build a unified platform that combines the best of Wear OS and Tizen. It should also provide the most popular features from Fitbit and support Material You design. It should also allow users to use offline storage, which can be used to listen to your favorite songs even without a smartphone or internet connection, for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*d1WktMPRlX7xfLsp.gif" /><figcaption>New Wear smartwatch system</figcaption></figure><h3>Privacy</h3><p>As for the last few years, privacy is still a crucial topic for Google that was addressed multiple times during the announcements of the new products. For example, Chrome allows users to delete the last few minutes of search history with a couple of taps. Photos will support a securely locked folder. All account activity data will be automatically deleted after 18 months and much more. Privacy is also one of the core themes of Android 12. The new privacy dashboard allows users to see who was accessing their data and will be able to revoke permissions for the apps from there easily. Changes also come to the location access. The new system will allow users to select if the app requesting the location should use precise or only approximate values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T8PGcp--a6BUwDLX.jpg" /><figcaption>New privacy dashboard in Android 12</figcaption></figure><h3>AI</h3><p>AI technologies are an integral part of the Google ecosystem. So it is not a big surprise that the engineers from Google are very actively working on new features for these products and new technologies. This year’s announcements contained many improvements throughout various products. From better memories and cinematic moments in the Photos via ecological and safe routes in the Maps to much better Google Assistant. The technologies worth mentioning are LaMDA and MUM. LaMDA (Language Model for Dialogue Applications) is breakthrough conversational technology trained on the dialog, which promises the next step of evolution to AI conversations across Google services. It was presented on the really rich dialogue with a model trained as dwarf-planet Pluto or paper plane. MUM (Multitask Unified Model) is a technology capable of multitasking to connect information for users in new ways. It can join data from multiple languages, images, videos, and even audio sources to gain deep knowledge of the world. With such knowledge, it should not be a problem to take a photo of boots and ask, “Can I use these to hike Mt. Fuji?”. A model trained with MUM should know and give you a sophisticated answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ac1TboOIbhuDXK1I" /><figcaption>Visualization of LaMDA (Language Model for Dialogue Applications)</figcaption></figure><h3>Jetpack Compose</h3><p>Although the previous announcements were interesting, for the Android developers in the Futured is the most important announcement the release date of the production-ready version of the Jetpack Compose. It is Android’s modern toolkit for building native declarative UI. So far, it was in the beta development stage with regular updates. But now, it should get a stable release in July. There are still some minor bugs and performance issues, but in a few months, we should get a version that will make the development of the native applications simpler, less bug-prone, and faster. We are looking forward to this date.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aq4T0BUUuaMpFhsPmqZbHA.png" /><figcaption>Sample of UI created with Jetpack Compose</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ff019847217" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#TheAndroidShow: Jetpack Compose - our thoughts]]></title>
            <link>https://medium.com/@sumera.martin/theandroidshow-jetpack-compose-our-thoughts-11fc4c3e4761?source=rss-2c37b2ce78c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/11fc4c3e4761</guid>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Martin Sumera]]></dc:creator>
            <pubDate>Thu, 25 Feb 2021 12:20:29 GMT</pubDate>
            <atom:updated>2021-02-25T12:20:29.598Z</atom:updated>
            <content:encoded><![CDATA[<h3>#TheAndroidShow: Jetpack Compose–our thoughts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDzeFwckRt8wH18Y6dJ3oA.png" /></figure><p>The first <em>#TheAndroidShow</em> focused on Jetpack Compose is over, and we are excited to share our thoughts about it with you.</p><p>Jetpack Compose is Android’s modern toolkit for building native declarative UI. So far it was in the alpha development stage. With each new version, many APIs have been changed, and it was tough to keep up with all the changes. When you skipped a few versions and didn’t read changelogs very carefully, you’ve had a good chance that your app wouldn’t work and the fix was not going to be easy. This shouldn’t be the case anymore since the promotion to the beta stage was announced during the show.</p><h4><strong>The first beta release</strong></h4><p>It didn’t take much time, and during the first few minutes, we’ve got an announcement about this new release (as we were expecting since Jetpack Compose is developed as an open-source project and the info about the <a href="https://android-review.googlesource.com/c/platform/frameworks/support/+/1586709">commit</a> with the version update was shared within the developer community the last few days).</p><p>The beta is an important milestone of almost two years of efforts to create a declarative UI system natively on the Android platform. The beta release should have a mostly stable API which means fewer breaking changes and thus easier development. It also brings many new resources for learning, a lot of missing features, and detailed samples.</p><p>But it mainly means that the native development on the Android platform is on a good track to keep up with modern paradigms making the development simpler, less bug-prone, and faster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VdFzkVFl9GaWc2m7hsnm1g.png" /><figcaption>Sample of UI defined with the Jetpack Compose</figcaption></figure><h4>What to expect in the future?</h4><p>Q&amp;A session gave us plenty of hints on what we can expect or look forward to. Since the amount of components is rich enough to build a complex app, the main concerns are slightly shifting towards performance, tooling and architecture of apps based on Jetpack Compose. It&#39;s important to note; the whole toolkit is managed as a Gradle dependency, so to get new features, optimizations and bugfixes, you don&#39;t have to wait until your user&#39;s phone receives an OS update.</p><p>From the performance perspective, we heard about the multithreaded evaluation of composable components. This is a revolutionary idea in the Android world, where UI can be accessed only from the Main thread.</p><p>One of the essential questions in compose world is state management and it is tightly coupled with selected architecture. Jetpack Compose is architecture agnostic and it can be used with a wide variety of architectures, such as MVI, Redux or MVVM. We are eager to watch what ends up as a recommended one.</p><h4>Is it production-ready?</h4><p>Well, not yet. As mentioned during the live Q&amp;A, even though it is possible to create really nice-looking applications, a few things are still missing, contain bugs, or have performance issues. But all these things should be added, fixed or improved in the following months. The release date for the stable release candidate was not officially announced. However, careful listeners noticed that they mentioned that it should be ready this year. That may sound like a lot of time, but I believe it will be prepared to use in the production environment even before that. Let’s use this time for preparation and make the transition to the new toolkit as smooth as possible.</p><h4>New #AndroidDevChallenge</h4><p>A new Android developer challenge was announced as the last thing of <em>#TheAndroidShow</em>. This challenge should help developers to learn some basic and advanced topics from the Jetpack Compose toolkit. During the four assignments, each taking a week to finish, the developers are expected to get their very own insights into Jetpack Compose. It’s a great way to motivate yourself and start working on real-world use cases. For each one of the weekly challenges, you can even win a lot of prizes.</p><p>The first challenge is the simple Puppy adoption app with a list of puppies and details about them. It’s a well-known fact that everything is better with puppies, even learning the new UI toolkit.</p><h4>What next?</h4><p>We are excited about the changes that the Jetpack Compose will bring us in the following months and even more curious about how it will affect the future of Android development. We expect a significant positive impact. So we are going to continue to watch its development very carefully.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11fc4c3e4761" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From custom view to Jetpack Compose]]></title>
            <link>https://medium.com/@sumera.martin/from-custom-view-to-jetpack-compose-5a95e8d76a9a?source=rss-2c37b2ce78c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a95e8d76a9a</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Martin Sumera]]></dc:creator>
            <pubDate>Wed, 27 May 2020 07:23:43 GMT</pubDate>
            <atom:updated>2020-05-27T07:23:43.331Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0xla6mw71PgMuT7gBgIPw.png" /></figure><p>Creating a Jetpack Compose equivalents of the “traditional” UI libraries for Android will be probably necessary if you want to keep up with new trends. In this article, you will learn how we did it and what new we learned from this process.</p><p>When you’re done reading the article, you will learn that</p><ul><li>creating a new component for Jetpack Compose is easy, once you will understand a little bit about its paradigm</li><li>reusing some things from the original implementation is good but don’t be afraid to write some things from the scratch</li><li>adding custom animations to components is not as difficult as it may seem</li></ul><p>It is always hard to keep up with new technologies, especially in the software development field. You always need to be prepared for new challenges and can’t be afraid of trying new things. One of these challenges for Android developers in the foreseeable future will be Jetpack Compose and its new paradigm of developing UI. That is one of the reasons why our company decided to do a little research a try to re-implement one of our UI libraries to the Jetpack Compose version to test its current capabilities.</p><h4>The original library</h4><p>Project 🍩 <a href="https://github.com/futuredapp/donut"><em>Donut</em></a> 🍩 is a library that creates doughnut-like chart views. It is highly customizable with many features and support for animations. Thus it was our great candidate for re-implementation from an “<em>old</em>” custom view to a “<em>new</em>” composable view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*UE_7WWcwEyd8WTAsjOTgiQ.gif" /><figcaption>The original Donut implementation</figcaption></figure><h4>Analysis and reusability</h4><p>The initial step of the new implementation was to analyze the original version of the library and find what can be reused in the new one. In simple terms, the original version is using the canvas from the overridden onDraw method in the custom view. The sections of the chart are calculated as paths based on the relatively simple algorithm. Then they are drawn onto a canvas. After a quick overview, we find out that from this implementation, we could take an algorithm, the way how the sections of the chart are drawn to the canvas, and partially also an interface of the view used by the developers using this library.</p><p>The algorithm is basically a calculation of how much of the whole donut should each section occupy. I don’t want to go into details because it is not very important for this article. However, I made some changes to the algorithm, and instead of the path, I’m calculating the start and sweep angle of each section, which seems to be a little bit simpler.</p><p>The canvas class, in the original implementation, is using only a drawPath method used to draw sections of the chart. Since we adapted our algorithm a little bit to calculate the start and sweep angle instead of the whole path, we are going to use the only drawArc method from the canvas. The Jetpack Compose provides it’s own custom version of the canvas that is similar to the canvas from the “<em>old</em>” way of drawing custom views.</p><h4>From XML to Data Class</h4><p>Composable views provide a completely different paradigm of dealing with UI changes. From the interface of the original implementation, we have reused the names of the properties and replaced their implementation in the XML and the custom view with a one simple model class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*b89IZ-7ooDovKKE5kZgIQg.png" /><figcaption>The XML definitions, setters, getters and properties of the original implementation</figcaption></figure><p>All these XML attributes, getters, setters, and properties were transformed into the following class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47ef155eca0cf0b92ff5058f4f2a8660/href">https://medium.com/media/47ef155eca0cf0b92ff5058f4f2a8660/href</a></iframe><p>The first big advantage of this change, which is visible in the previous code samples, is the reduced amount of the code (most of it is boilerplate code) required to define all these properties. We don’t have to define getters, setters, XML definitions, or attributes obtaining. So 18 lines of the code used just for the definition of the strokeWidth property with all necessary methods became just 1 line.</p><p>DonutData class doesn’t contain anything particularly new for someone who knows a little bit of Kotlin except for @Model annotation. This annotation transforms data class into an observable class that will cause a recomposition of the layouts, which are observing its properties, whenever any of them is changed. Eg. When we change gapWidthDegrees property, then the donut view will automatically recompose views that are dependant on these properties and will draw a new layout.</p><h4>Dive into @Composable world</h4><p>The next step is the definition of the composable view. It is just a plain method with the @Composable annotation that is accepting DonutModel as a parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/525e6253a13dca93abaad340aefa0cb8/href">https://medium.com/media/525e6253a13dca93abaad340aefa0cb8/href</a></iframe><p>The body of this method consists of two basic things. The algorithm (1), which is just a plain Kotlin function that calculates and returns all necessary values required for the drawing of the donut (angles, position, rotations, etc). And another composable private function (2) responsible for drawing of the donut from previously calculated data to the canvas.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6b6c774e2b091a42b7a69860191895d/href">https://medium.com/media/b6b6c774e2b091a42b7a69860191895d/href</a></iframe><p>DrawDonutInternal consists of four main parts. We obtain a Paint object from the “cache” via the remember { … } function (1) (we are going to get into details of this in the few lines). Then, we create a canvas object used to draw a donut (2). Within the onCanvas method, we draw a background line of the donut (3), and finally, we draw all sections of the donut (4).</p><p>The implementation of the <em>getPaintFromCache</em> method looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5ec9e909a5553c769f36013fb31f4ce/href">https://medium.com/media/f5ec9e909a5553c769f36013fb31f4ce/href</a></iframe><p>The remember { … } function initializes the Paint object only once, during the first composition. This value is cached and every time during recomposition of this composable function it will return the same instance of the Paint object. The only thing that is dynamically changed is the strokeWidth parameter since it is an animatable property. Without the remember { … } function, the Paint object would be created for each recomposition, and that could cause unnecessary memory overhead.</p><p>The implementation of the drawDonutSegment function looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6171cd4aa97ed8c8c1688c72779de85e/href">https://medium.com/media/6171cd4aa97ed8c8c1688c72779de85e/href</a></iframe><p>First, we calculate the bounds of the donut defined as a Rect (rectangle) object. Then we draw an arc of the donut section onto the canvas within the area of these bounds.</p><h4>We are halfway there</h4><p>In this state, the new implementation of Donut works as expected. The following code creates a new doughnut-like chart 🍩</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/032d7f26655f2607a61c3b33cdeaa854/href">https://medium.com/media/032d7f26655f2607a61c3b33cdeaa854/href</a></iframe><p>When we add some more controls and overview in the middle, we get the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*beW_FBSQxzl11UIoufohXA.gif" /></figure><p>However, there is one “<em>small</em>” thing missing: animations.</p><h4>Animation setup</h4><p>Original Donut implementation allows us to animate only a few most important features. In our new implementation, we want it to extend it even more further and enable developers to use animations even more extensively. We know that everybody likes pretty and smooth animations, but we also know that sometimes you need to disable or customize them to get a perfect result. For this purpose, we create a new DonutConfig class and annotate it with @Model annotation. It contains properties for enabling animations (Boolean) and customization of animations (AnimationBuilder) for each property from the DonutData that we wish to have an ability to be animated. In our case, it is every property of DonutData 🤷‍♂ Some of these properties may seem irrelevant, and animation won’t make sense for them at first sight. Still, it’s better to leave it to the developers and their creativity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86a764c93f85813aa6078f80c687d853/href">https://medium.com/media/86a764c93f85813aa6078f80c687d853/href</a></iframe><p>DonutConfig contains a new AnimationBuilder class that serves as some kind of animation interpolator (but it is actually much more). Do you want to use some predefined or custom easing? TweenBuilder is there for you. Do you want to use spring animations? PhysicsBuilder is there also for you. Do you want just to snap an animated value to the target value right away?SnapBuilder. You have a lot of options here that allow you to customize each animation separately.</p><p>DonutConfig is implemented, and it is time to update our composable function DonutProgress.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c463b79e5a5383b236fb42470759ca6/href">https://medium.com/media/4c463b79e5a5383b236fb42470759ca6/href</a></iframe><p>We have added a default value for the config property with all animations enabled since we do not want to bother a developer with these things unless he decides that he wants to change them.</p><h4>Animation implementation</h4><p>Now we are going to implement the animations. Since many things in the Jetpack Compose are still in development and only poor documentation is provided so far, we must dive into source code and samples to find out how to deal with this issue. I found three possible ways of handling animations:</p><ul><li>From the outside by dynamically changing values in the model <em>(Bad solution. You are moving all these responsibilities and work to the developer and thus making his life harder, not easier)</em></li><li>Transitions <em>(Good solution for animating predefined states but that is not very suitable for our purpose)</em></li><li>AnimatedValue (<em>Bingo</em> 🎉)</li></ul><p>The AnimatedValue is a class that can animate its generic internal value. It is annotated with @Model annotation. It means that each change of the value causes a recomposition of the layout that is using this value. The animation is started with the animateTo method. Once this method is called, the class starts to observe the animation clock and recalculates animated value on each animation frame defined by the clock, so all the animation magic happens inside of this class. Jetpack Compose takes care of observing these changes and recomposing layout dependent on them.</p><h4>Magic behind animatedFloat</h4><p>Each animatable property is transformed with the animatedFloat (or animatedColor) method in order to initialize AnimatedValue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e100342c5b20dc3117954167d8ab52e2/href">https://medium.com/media/e100342c5b20dc3117954167d8ab52e2/href</a></iframe><p>The animatedFloat is a composable function that returns a remembered (cached) AnimatedFloat object. The AnimatedFloat object returned from this method always has the same instance even after layout recomposition. It holds the initial value even when the gapAngleDegrees property is changed. In order to change the value of this object, we have to set a new target value to which the object animates its internal value. Until the animation process is not started with animateTo or some other animation method, the value of the animatedGapAngle won’t be changed even when initial data are changed. This method is a part of the Jetpack Compose and is implemented this way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e537c564a221f5e7641d232ca2981fa1/href">https://medium.com/media/e537c564a221f5e7641d232ca2981fa1/href</a></iframe><p>It has a few important things that we should notice and understand to find out how this animation technique is working. <strong>AnimationClockAmbient</strong>, <strong>remember</strong>and <strong>AnimatedFloatValue</strong>.</p><p>In quick terms, an Ambient in the Jetpack Compose is a mechanism that lets you pass some kind of dependencies through the layout tree without having to put them explicitly in the method signature. It’s just there in the background waiting for you to use it whenever you need it. (Eg. ContextAmbient.current returns Context, so you can call it from anywhere within composable functions where it is needed). <strong>AnimationClockAmbient</strong> provides a clock that notifies us whenever new animated value should be recalculated. <strong>remember { … }</strong>, as we already learned, provides some kind of cache mechanism that makes sure that the AnimatedFloatValue is instantiated only once and with an initial value. <strong>AnimatedFloatValue</strong> is a subclass of AnimatedValue that animates float values.</p><h4>Extending BaseAnimatedValue</h4><p>AnimatedValue has two public methods that are interesting for us animateTo and snapTo. Since we want to animate our properties only when they are changed and enabled, we use the following extension method that helps us with this logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b37d5144de2526cb375e6d430d33e546/href">https://medium.com/media/b37d5144de2526cb375e6d430d33e546/href</a></iframe><p>If the new value is the same as the target value, then it does nothing since we do not want to trigger the same animation again. If the value is not the same, then it checks if the animation is enabled, and if it is, then it starts an animation process. Otherwise, it just snaps it to the final value.</p><h4>Gluing it together</h4><p>Now, we need to glue all these things together. If we would like to animate only one property, then the implementation of DonutProgress could look somehow like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45099a978719318cb02e1e84fa8e987e/href">https://medium.com/media/45099a978719318cb02e1e84fa8e987e/href</a></iframe><p>The change of the gapAngleDegrees property causes DonutProgress to recompose. That causes the execution of the animateTo method of animatedGapAngle, which means that the animation is started. That change is observed by Jetpack Compose and it causes a recomposition of the DrawDonut composable function. It is recomposed multiple times with an updated animated value until the animation is stopped. This approach allows us to animate multiple properties at the same time with very little management and without worrying about interfering with each other.</p><p>Since we have multiple animated properties, the actual implementation looks more like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1aaa8a388d8c2c16e047fc2cefb63b7/href">https://medium.com/media/a1aaa8a388d8c2c16e047fc2cefb63b7/href</a></iframe><p>All animated properties are wrapped in the wrapper class (1.), then they are animated if necessary (2.), and then they are passed to the DrawDonut, which takes care of drawing it onto canvas (3.).</p><p>Now, we need to update our algorithm inside DrawDonut to work with the animated values instead of the values directly provided by DonutData.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bbcd2a6320dcbe9ed9ecb9b9befc117/href">https://medium.com/media/7bbcd2a6320dcbe9ed9ecb9b9befc117/href</a></iframe><p>It is a very simple change. Each direct access of properties from DonutData is just replaced with their animated counterpart.</p><h4>The result</h4><p>That’s All Folks 🎉 Jetpack Compose implementation is successfully finished.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*N1Io6WB3KMHbQL1gGXdK6g.gif" /><figcaption>The Jetpack Compose Donut implementation</figcaption></figure><p>We successfully implemented a delicious donut in Jetpack Compose with extensive customization and animation support. A new UI paradigm forced us to implement it differently, but we were able to reuse some parts of the logic from the original implementation also. It took some time and effort to figure out how Jetpack Compose works internally, but once we got into it and understood it, then the work became very intuitive. We also learned that creating animations in Jetpack Compose is not as difficult as it seems at first glance. And last but not least we transformed all these XML definitions and custom methods of our library to much more compact, readable, and simpler definitions.</p><p>Donut definition for traditional Android view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b89IZ-7ooDovKKE5kZgIQg.png" /><figcaption>Traditional Android view</figcaption></figure><p>Donut definition for Jetpack Compose:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7805fa178abf859a21277c5e904aee90/href">https://medium.com/media/7805fa178abf859a21277c5e904aee90/href</a></iframe><p>For more details on Donut library, check our <a href="https://github.com/futuredapp/donut">Github</a> page and for more details about the details of the new Jetpack Compose implementation check, <a href="https://github.com/futuredapp/donut/blob/master/libraryCompose/src/main/java/app/futured/donut/library/compose/Donut.kt">this file</a> with all implementation details.</p><p><a href="https://github.com/futuredapp/donut">futuredapp/donut</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a95e8d76a9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bring RxLifecycle to presenter world]]></title>
            <link>https://medium.com/@sumera.martin/bring-rxlifecycle-to-presenter-world-703d0da5d6d1?source=rss-2c37b2ce78c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/703d0da5d6d1</guid>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Martin Sumera]]></dc:creator>
            <pubDate>Tue, 17 Jan 2017 09:02:00 GMT</pubDate>
            <atom:updated>2017-01-17T09:08:43.604Z</atom:updated>
            <content:encoded><![CDATA[<p>Reactive programming is a very useful paradigm that brings us a simple way to deal with multithreading in Android development. When we need to get data from a server, we can implement it using following steps:</p><ul><li>Create an <em>Observable</em> which sends request to a server</li><li>Subscribe to this <em>Observable</em></li><li>Wait for the data</li><li>Process the data</li></ul><p>It is really simple except one missing part - unsubscription. If you forget to implement one of the steps above, your program will not compile or will not act as you would expect. But if you forget to unsubscribe from an observable, you risk memory leaks or some unexpected behaviour, that can occur only in some edge cases.</p><p>A simple way to unsubscribe is to take a reference of subscription and call <em>unsubscribe()</em> during the expected state of a lifecycle. But this leads into a lot of boilerplate code and can be easily forgotten.</p><p>The guys at Trello faced same issue and decided to help by releasing the <a href="https://github.com/trello/RxLifecycle">RxLifecycle</a>, an Android library that will automatically manage the unsubscribe routine based on the lifecycle of the target activity or fragment.</p><p>RxLifecycle simplifies the process of unsubscribing and can be used not only with an android objects, but with any object with its own lifecycle. This article will show you how to extend this library to be used with presenters instead of activities or fragments.</p><h3>How to use RxLifecycle</h3><p>Usage is very simple. Your activity needs to extend RxActivity and add simple <em>compose()</em> method before a subscription.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f4e49d9464fc05d6c77b1ada07a0815/href">https://medium.com/media/7f4e49d9464fc05d6c77b1ada07a0815/href</a></iframe><p>🎉 “<em>TA-DA!!</em>” 🎉 our <em>Observable</em> terminates during <em>onDestroy()</em>.</p><p>The important thing is to remember how RxLifecycle termination of sequences works:</p><blockquote>RxLifecycle does not actually unsubscribe the sequence. Instead it terminates the sequence. The way in which it does so varies based on the type:</blockquote><blockquote>Observable — emits onCompleted()</blockquote><blockquote>Single and Completable — emits onError(CancelationException)</blockquote><h3>How RxLifecycle works internally</h3><p>RxLifecycle has a very well-structured code. Base module of the library contains the whole “<em>magic</em>”, which transforms our <em>Observable</em> into another one that observes lifecycle events. So it can work independently from activities and fragments.</p><p>Base lifecycle object (such as activity, fragment) implements <em>BehaviorSubject</em> which observes individual lifecycle events. It means that during <em>onCreate()</em>, the lifecycle subject observes the <em>CREATE</em> event, during <em>onDestroy()</em> it observes the <em>DESTROY</em> and so on…</p><p>Then, before subscription, we need to pass this lifecycle subject into <em>RxLifecycle.bind() </em>method, that will transform our <em>Observable</em> into a new one which observes emitted items from the lifecycle subject. And when it observes expected termination event, <em>Observable</em> terminates itself.</p><h3><strong>What about presenters?</strong></h3><p>Obviously, we are good boys who care about clean code and good architecture of our apps and we would like to bring similar concept into the MVP, where presenter should take care of a presentation logic.</p><p>One way to solve this problem is to take the lifecycle from an activity and pass it into a presenter. But it’s not the cleanest solution because it violates encapsulation principle of OOP.</p><p>And what if we want to add another lifecycle event into the presenter and terminate our Observable during <em>onViewStop()</em>? If we used the lifecycle from an activity, our code would look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ec0dc1ba0c910bf3701e9305b71364e/href">https://medium.com/media/4ec0dc1ba0c910bf3701e9305b71364e/href</a></iframe><p>We would need to call <em>bindUntilEvent()</em> and add <em>ActivityEvent.STOP</em> as a parameter. So, presenter must be aware of the internal implementation of the view. And when we change activity into a fragment we will also need to change implementation of the presenter.</p><p>The solution to this problem is to use lifecycle of a presenter. Our example presenter has only two lifecycle methods, <em>attachView()</em> and <em>detachView()</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7029e2f9f181caaf2b5b44a1ebd62d9/href">https://medium.com/media/e7029e2f9f181caaf2b5b44a1ebd62d9/href</a></iframe><p>But if you want to add other methods, <em>onStop()</em> for example, you can do it very easily.</p><h3>Let the coding begin</h3><p>Firstly, we need to define a data type which will represent individual states of a lifecycle. So for each we define the unique integer constant <em>(RxLifecycle internally uses enums, but that isn’t the </em><a href="https://www.youtube.com/watch?v=Hzs6OBcvNQE"><em>Android way</em></a><em>)</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1141be33be03c1d2b2c74768b8b2f583/href">https://medium.com/media/1141be33be03c1d2b2c74768b8b2f583/href</a></iframe><p>Now we must define a function that describes the order of lifecycle events. This function takes the current lifecycle state as an argument, and returns the next state. For the first state we return the second, for the second we return the third and so on. The last state throws the <em>OutsideLifecycleException</em>, which indicates that the <em>DETACH</em> event was the last lifecycle state of the presenter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02e4ae6de3194fdeef5ece423cd574f6/href">https://medium.com/media/02e4ae6de3194fdeef5ece423cd574f6/href</a></iframe><p>We also need to define the <em>RxLifecyclePresenter</em> class that will bind the lifecycle function into the RxLifecycle library. This class has only one public method <em>bindPresenter()</em> that takes an <em>Observable</em> as an argument that emits lifecycle states.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b77e1997699355a23b2b1e8c06720e3e/href">https://medium.com/media/b77e1997699355a23b2b1e8c06720e3e/href</a></iframe><p>Now we have everything we need to add this functionality into a presenter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6494c20cc8e14102fe80dee29ba665a/href">https://medium.com/media/f6494c20cc8e14102fe80dee29ba665a/href</a></iframe><p>We added lifecycleSubject and during the <em>attachView()</em> and the <em>detachView()</em> we pass lifecycle arguments into it.</p><p>Next, we need to implement the <em>LifecycleProvider&lt;Integer&gt;</em> interface, which contains three methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98f605fba6e2d47070c6f227c9442c53/href">https://medium.com/media/98f605fba6e2d47070c6f227c9442c53/href</a></iframe><ul><li><em>lifecycle()</em> returns the lifecycle subject as an <em>Observable</em>.</li><li><em>bindToLifecycle()</em> returns a <em>LifecycleTransformer</em> object, which transforms our <em>Observable</em> into new one with bound lifecycle.</li><li><em>bindUntilEvent(event)</em> is similar as the method before, but we can pass a different termination state as a parameter. (<em>STOP</em>, <em>RESET</em> … )</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a685257af12d8b80c3f170f5c8decf30/href">https://medium.com/media/a685257af12d8b80c3f170f5c8decf30/href</a></iframe><p>Now we are ready to use it. Extend the <em>BaseLifecyclePresenter</em> and add a <em>bindToLifecycle()</em> method into <em>Observable</em>, which will be terminated during <em>detachView()</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/396d164225ada58659000395f9333494/href">https://medium.com/media/396d164225ada58659000395f9333494/href</a></iframe><h3>Conclusion</h3><p>Adding new components to the RxLifecycle library is really simple and can be extended to any kind of object with its own lifecycle methods.</p><p>You can find the whole project with all examples on <a href="https://github.com/SumeraMartin/RxLifecyclePresenter">github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=703d0da5d6d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>