<?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 Alex Zaitsev on Medium]]></title>
        <description><![CDATA[Stories by Alex Zaitsev on Medium]]></description>
        <link>https://medium.com/@alexzaitsev?source=rss-6c59eafdbea8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mPke2d9xIwiDI-IDEnIZrA.jpeg</url>
            <title>Stories by Alex Zaitsev on Medium</title>
            <link>https://medium.com/@alexzaitsev?source=rss-6c59eafdbea8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 14:56:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexzaitsev/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[How businesses already can benefit from Kotlin Multiplatform and Compose Multiplatform]]></title>
            <link>https://medium.com/@alexzaitsev/how-businesses-already-can-benefit-on-kotlin-multiplatform-and-compose-multiplatform-699e51b7f2f6?source=rss-6c59eafdbea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/699e51b7f2f6</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[crossplatform-mobile-app]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Alex Zaitsev]]></dc:creator>
            <pubDate>Wed, 31 May 2023 03:52:45 GMT</pubDate>
            <atom:updated>2023-05-31T04:13:40.349Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CpRVtFudFD2fmhzlBS-dsw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mbrunacr?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Miguel Bruna</a> on <a href="https://unsplash.com/photos/TzVN0xQhWaQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote>This post is written mostly for business owners, mobile engineering managers, team leads, etc.</blockquote><p><strong>Whether you’re going to start a new mobile project in 2023 or maintain an ongoing one, this article will give you an understanding of where the ecosystem is and how to make the most profit from it.</strong></p><p>Now we can build smooth mobile cross-platform apps (both iOS &amp; Android) with <a href="https://kotlinlang.org/docs/multiplatform-mobile-getting-started.html">Kotlin Multiplatform</a> (shared logic) and <a href="https://www.jetbrains.com/lp/compose-multiplatform/">Compose Multiplatform</a> (shared UI).</p><h3>What does it mean for your business?</h3><p>1. <em>Significant cut of the workforce, first of all. </em>An average mobile team consists of 4–5 developers (the actual number can vary from 1–2 to 30+ for huge projects like Spotify). Going multiplatform cuts at least 1/3rd of the team. Maybe half if you’re a manager virtuoso.</p><p>2. <em>Another benefit is more stable apps. </em>Multiplatform means the code needs to be covered by the tests only once. It can include both unit tests and automated testing. Manual QA time is going to be reduced as well.</p><p>3. <em>Faster development time.</em> As we already have a lot of <a href="https://developer.android.com/jetpack/compose">Jetpack Compose</a> libraries that have already migrated to <a href="https://kotlinlang.org/docs/multiplatform-mobile-getting-started.html">KMM</a>, multiplatform development is getting as easy as <a href="https://www.udemy.com/course/modern-android-architecture/?referralCode=AA60BFC9B867AD172067">modern Android development approaches</a>.</p><p><strong><em>Sounds too sweet? Let’s dive deeper.</em></strong></p><h3>What about other cross-platform frameworks?</h3><p>The main competitor for KMM and CM is <a href="https://flutter.dev/">Flutter</a>, of course. However, a huge benefit of KMM is <em>reduced learning time</em>. It means that <em>ANY</em> Android developer who already knows Jetpack Compose and its architectural approach can switch to KMM &amp; CM <em>in less than a week</em>.</p><p>Compare it to Flutter now! Flutter uses <a href="https://dart.dev/">Dart</a> programming language. It has to be learned and it’s a significant effort that has to be made by developers. Going Kotlin Multiplatform we reuse what we already know and don’t need to waste our time learning the language that can be applied only for Flutter projects.</p><p>I mean that if your developers know Kotlin they can write the backend in it. Of course, it may be not a good idea to share human resources between frontend and backend but the fact that the whole ecosystem is made in a single language means the team is able to do cross-code reviews. Frontend and backend developers can speak the same language! It eliminates the barriers.</p><p><strong><em>I’m trying to say that it’s more beneficial for both developer and employer to work with KMM rather than with Flutter or any other cross-platform framework.</em></strong></p><h3>What about nocode?</h3><p>Nocode is one more possible approach. Take <a href="https://flutterflow.io/">FlutterFlow</a> as an example. There are several pitfalls, though.</p><p>While it can be an excellent choice for the fast PoC, this approach fails as your system grows. It’s hard to build sustainable and scalable architecture with nocode.</p><p>Even if you’re not bothered with the growth, another pitfall can be using platform-specific APIs and writing custom UI components. It’s barely achievable in nocode tool. Anything related to video streaming most probably will fail too as this part should be written in each platform separately.</p><p><strong><em>So, nocode can be a solution but only for short-life or non-complex projects. For everything other, you still need a decent development team.</em></strong></p><h3>Final thoughts</h3><p><strong>CM of top KMM is a game changer. It makes old developers’ dream of writing true shared multiplatform code a real thing. Businesses can already benefit from this.</strong></p><p><strong>Interested? Reach out, let’s discuss what’s on top of your mind. </strong><a href="https://www.linkedin.com/in/alex-zaitsev-android/"><strong>My LinkedIn</strong></a><strong>.</strong></p><p><em>If you’re an Android developer and haven’t tried Jetpack Compose yet or struggling with the architecture I highly encourage you to take </em><a href="https://www.udemy.com/course/modern-android-architecture/?referralCode=AA60BFC9B867AD172067"><em>my Udemy course</em></a><em>. It’ll take another week for you to go through it but you’ll be surprised with the final result, I promise. You’ll be able to start developing KMM &amp; CM on top of that knowledge as it’s 100% transferrable to multiplatform development.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=699e51b7f2f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Android Architecture course announcement]]></title>
            <link>https://mobileappcircular.com/modern-android-architecture-course-announcement-75ed16630e7e?source=rss-6c59eafdbea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/75ed16630e7e</guid>
            <category><![CDATA[android-architecture]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[udemycourses]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alex Zaitsev]]></dc:creator>
            <pubDate>Wed, 26 Apr 2023 04:57:11 GMT</pubDate>
            <atom:updated>2023-04-28T06:42:35.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*VxRExSgEoMFH7o06-oIPRw.png" /><figcaption>Modern Android Architecture</figcaption></figure><h3>I am excited to announce the launch of my ‘Modern Android Architecture’ Udemy course!</h3><p>This course is designed for <strong>all levels of Middle/Senior Android developers</strong> who wish to advance their knowledge on how to create cutting-edge, scalable, and maintainable Android applications.</p><p>Throughout the course, you will learn how to <strong>apply the Clean Architecture</strong> approach to your app development process, to create a codebase that is easy to understand, maintain, and extend. You will also learn how to <strong>leverage the Android Compose</strong> framework to <strong>build user interfaces that are reactive, declarative, and easy to test</strong>.</p><p>You will discover the ideas and abilities required to master Modern Android Jetpack Compose-based Clean Architecture in this course, which is organized into a series of lectures and practical activities.</p><h3>Link to the course <a href="https://www.udemy.com/course/modern-android-architecture/?referralCode=AA60BFC9B867AD172067">is here</a> (my referral code is applied).</h3><h4><strong>More precisely, you’ll learn how to:</strong></h4><ol><li>Learn how to create contemporary Android applications that are scalable and maintainable utilizing the newest tools and technologies.</li><li>Apply the Layered Clean Architecture approach to your app development process.</li><li>Start creating codebases that are simple to comprehend, extend, and maintain.</li><li>Understand how the codebase is evolving over time and what critical points you should pay attention to.</li><li>Learn how to use the Jetpack Compose framework to build user interfaces that are reactive, declarative, and easy to test.</li><li>Use reactive programming techniques to create responsive and scalable apps.</li><li>Benefit of using MVI presentational pattern for easier codebase on a view layer.</li><li>Understand how to test and debug Modern Android Architecture.</li></ol><p>By the end of this course, <strong>you will master the art of architecture extension</strong> (scalability). That means that <strong>you’ll be able to start with a modest codebase that</strong>, if necessary, <strong>may be quickly developed into a large application.</strong></p><p>You will have the skills required to <strong>launch a new project</strong> or <strong>convert an outdated codebase</strong> into a <strong>professional, modern, scalable, and well-maintained Android application</strong>. You will be able to <strong>reliably provide top-notch apps to your users</strong> by applying the Layered Architecture principles, Jetpack Compose framework, and MVI presentational pattern to your projects.</p><p>I’ll walk you through starting with a small codebase, explaining when it has to be extended, and exactly how to do it, starting with the architectural approach and tools and concluding with the structure of the code and files.</p><h4><strong>The course consists of:</strong></h4><ul><li><em>19 lectures (+1 bonus!)</em></li><li><em>100 minutes of the high-quality video content</em></li><li><em>4 quizzes</em></li><li><em>2 gists</em></li><li><em>1 complete test project that will be developed through the course (available on Github!)</em></li><li><em>A LOT of insights! I promise!</em></li></ul><p><strong>All the materials leave with you forever</strong>, so you always can use code samples and test project supplied in this course as a guide for your development.</p><h4>Link to the course <a href="https://www.udemy.com/course/modern-android-architecture/?referralCode=AA60BFC9B867AD172067">is here</a> (my referral code is applied).</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75ed16630e7e" width="1" height="1" alt=""><hr><p><a href="https://mobileappcircular.com/modern-android-architecture-course-announcement-75ed16630e7e">Modern Android Architecture course announcement</a> was originally published in <a href="https://mobileappcircular.com/">Mobile App Circular</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to display HTML using Android Compose]]></title>
            <link>https://proandroiddev.com/how-to-display-html-using-android-compose-c59e24ec0c6f?source=rss-6c59eafdbea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c59e24ec0c6f</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-compose]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Alex Zaitsev]]></dc:creator>
            <pubDate>Mon, 27 Jun 2022 10:24:58 GMT</pubDate>
            <atom:updated>2022-06-27T18:44:40.847Z</atom:updated>
            <content:encoded><![CDATA[<p>The reason for writing this article is that Text composable function does not support HTML yet. Since there are plenty of utility libraries that try to archive the same, I chose the way of my implementation as it’s flexible and adjustable to my needs.</p><p><strong>Requirements. I need:</strong></p><ol><li>Fonts support.</li><li>Text styling.</li><li>Links support! This is especially important for me since my app is using in-app web-viewer to display any links.</li></ol><p>Let’s see how each of the points archived. To make things clear — at high level this is just a wrapper for Android view. <a href="https://gist.github.com/alexzaitsev/060fc607d5a16eeef17276bb57e0914f">Full gist for this article</a>.</p><h3>The entrance</h3><p>Start from <a href="https://gist.github.com/alexzaitsev/060fc607d5a16eeef17276bb57e0914f#file-htmltext-kt">HtmlText.kt</a>. For now, read as least the method signature:</p><pre>@Composable<br>fun HtmlText(<br>    modifier: Modifier = Modifier,    <br>    html: String,<br>    textStyle: TextStyle = Typography.body1,<br>    onLink1Clicked: (() -&gt; Unit)? = null,<br>    onLink2Clicked: (() -&gt; Unit)? = null<br>)</pre><h3>Fonts support</h3><p>Refer to TypefaceSpanCompat.kt in <a href="https://gist.github.com/alexzaitsev/060fc607d5a16eeef17276bb57e0914f#file-typefacespancompat-kt">the gist</a>.</p><p>In HtmlText.kt pay attention to these lines:</p><pre>val fontResId = when (textStyle.fontWeight) {<br>    FontWeight.Medium -&gt; R.font.<em>inter_medium<br>    </em>else -&gt; R.font.<em>inter_regular<br></em>}<br>val font = ResourcesCompat.getFont(context, fontResId)</pre><p>How to connect TypefaceSpanCompat.kt with HtmlText.kt will be explained a bit later.</p><h3>Text styling</h3><p>By default HtmlText composable takes body1 TextStyle:</p><pre>textStyle: TextStyle = <em>Typography</em>.body1,</pre><p>And then maps it to classical Android parameters. As an example let’s look to the Gravity:</p><pre>val gravity = when (textStyle.textAlign) {<br>    TextAlign.Center -&gt; Gravity.<em>CENTER<br>    </em>TextAlign.End -&gt; Gravity.<em>END<br>    </em>else -&gt; Gravity.<em>START<br></em>}</pre><p>TextStyle can be easily modified. Example:</p><pre>HtmlText(<br>    html = stringResource(id = R.string.<em>create_drive</em>),<br>    textStyle = <em>Typography</em>.body1.copy(textAlign = TextAlign.Center, color = <em>Secondary</em>),<br>    onLink1Clicked = onLearnMoreClicked<br>)</pre><h3>Links support</h3><p>In HtmlText there are the next lines:</p><pre>movementMethod = DefaultLinkMovementMethod() { link -&gt;<br>    when (link) {<br>       LINK_1 -&gt; onLink1Clicked?.invoke()<br>       LINK_2 -&gt; onLink2Clicked?.invoke()                   <br>    }<br>    true<br>}</pre><p>What is DefaultLinkMovementMethod? This is a java class copy-pasted from Stackoverflow that just changes spans under the hood to make onLinkClick methods possible. You may read the whole code <a href="https://gist.github.com/alexzaitsev/060fc607d5a16eeef17276bb57e0914f#file-defaultlinkmovementmethod-java">here</a>.</p><h4>Links styling</h4><p>Another thing is links styling. In HtmlText you may see this line:</p><pre>setLinkTextColor(<em>Primary</em>.<em>toArgb</em>())</pre><p>Another things is links underline. My design requires it to be removed. Refer to Spannable.removeLinksUnderline below.</p><h3>Combining everything together</h3><p>In HtmlText there is a line:</p><pre>update = <strong>{ it</strong>.<em>text </em>= <em>fromHtml</em>(<strong>it</strong>.<em>context</em>, html) <strong>}</strong>,</pre><p>Where fromHtml is a custom method. Let’s look at it <a href="https://gist.github.com/alexzaitsev/060fc607d5a16eeef17276bb57e0914f#file-fromhtml-kt">here</a>.</p><p>At first, it takes a string and makes a Spannable from it:</p><pre>private fun parse(html: String): Spannable =                                             (HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_COMPACT) as Spannable)</pre><p>And then several Spannable transformations are made:</p><ol><li>Links underlines are removed in Spannable.removeLinksUnderline()</li><li>Spannable.styleBold(context: Context) :</li></ol><ul><li>makes bold parts black (the default text for my HtmlText composables is gray but I want the bold parts to be black);</li><li>sets a dedicated font for the bold parts.</li></ul><h3>strings.xml</h3><p>Finally, it’s important to show how I declare strings. This is a regular string with HTML (no links):</p><pre>&lt;string name=&quot;view_recovery_description&quot;&gt;<br>    &lt;![CDATA[<br>    &lt;b&gt;For your eyes only!&lt;/b&gt; Anyone who has access to your 12 word recovery phrase can access your entire wallet. Learn more<br>    ]]&gt;<br>&lt;/string&gt;</pre><p>And this is the same text but with the link:</p><pre>&lt;string name=&quot;view_recovery_description&quot;&gt;<br>    &lt;![CDATA[<br>    &lt;b&gt;For your eyes only!&lt;/b&gt; Anyone who has access to your 12 word recovery phrase can access your entire wallet. &lt;a href=&quot;link_1&quot;&gt;Learn more&lt;/a&gt;<br>    ]]&gt;<br>&lt;/string&gt;</pre><p>As you see, I’m using link_1 and link_2 hrefs to declare a link. Later, in a callback I can do whenever I want. In my case, I open a build-in browser page to handle it.</p><h3>Visual example</h3><p>That’s it! With ~100 lines of code we are now able to display almost any HTML. Let’s look at the example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CIOJ5xXZo98Mv4B0i1_N2w.png" /></figure><p>String for this example:</p><pre>&lt;string name=&quot;create_drive_pass_description&quot;&gt;<br>    &lt;![CDATA[<br>    This password protects your Google Drive backups. &lt;b&gt;Store this password somewhere safe.&lt;/b&gt; We cannot recover your password for you. &lt;a href=&quot;link_1&quot;&gt;Learn more&lt;/a&gt;<br>    ]]&gt;<br>&lt;/string&gt;</pre><p>Code:</p><pre>HtmlText(<br>    modifier = Modifier.<em>padding</em>(top = <em>SIZE_16</em>, bottom = <em>SIZE_32</em>),<br>    html = stringResource(id = R.string.<em>create_drive_pass_description</em>),<br>    textStyle = <em>Typography</em>.body1.copy(textAlign = TextAlign.Center, color = <em>Secondary</em>),<br>    onLink1Clicked = onLearnMoreClicked<br>)</pre><p>That’s it! Thank you for reading.</p><p>You can support my work by clapping this article or sharing it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c59e24ec0c6f" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/how-to-display-html-using-android-compose-c59e24ec0c6f">How to display HTML using Android Compose</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Follow these simple Kotlin rules to write unbreakable code and stay 99+% crash-free]]></title>
            <link>https://levelup.gitconnected.com/follow-these-simple-kotlin-rules-to-write-unbreakable-code-and-stay-99-crash-free-83752ad4fcc3?source=rss-6c59eafdbea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/83752ad4fcc3</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alex Zaitsev]]></dc:creator>
            <pubDate>Sat, 12 Mar 2022 17:08:56 GMT</pubDate>
            <atom:updated>2022-04-05T01:55:06.946Z</atom:updated>
            <content:encoded><![CDATA[<h3>Follow these simple Kotlin rules to write unbreakable code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GyatlXoPFSHTRjLQ" /><figcaption>Photo by <a href="https://unsplash.com/@polygonglider?utm_source=medium&amp;utm_medium=referral">Michael</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When Kotlin was introduced to Android developers it was something different from the usual Java world. Nullability — what a sweet idea! A lot of syntactic sugar and so on. However, after years of usage, I see how easy is to break the design.</p><p><strong>How to avoid shooting the leg and make your code unbreakable?</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F10Mn81By5JVRnO%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F10Mn81By5JVRnO%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F10Mn81By5JVRnO%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/f46e1fd68a89c1c01e2cf62702f67d83/href">https://medium.com/media/f46e1fd68a89c1c01e2cf62702f67d83/href</a></iframe><p>The answer is easy — <strong>design the code in a way that it would be impossible (or hard) to introduce the bug</strong>.</p><p>Let’s look at a couple of things that can be done.</p><h3>Nullability</h3><p>Speaking at a software conference in 2009, <a href="https://en.wikipedia.org/wiki/Tony_Hoare">Tony Hoare</a> apologized for inventing the null reference: “<em>I call it my billion-dollar mistake.</em>”</p><p>Kotlin fixes it but it also <em>allows</em> to disregard the design.</p><h4>!! operator</h4><p>!! operator is one of the most dangerous things. I urge the reader — write !!-free programs. Even if you are 100% sure <em>this reference </em>cannot ever be null — actually it can. Not now but in the nearest future when your colleague (or you) change the code.</p><p>The rule is simple. <strong>Be paranoid. If something can break — it will.</strong></p><p>So never ever use !! operator in native Kotlin code.</p><h4>lateinit var</h4><p>At first, this Kotlin feature may seem like something convenient and trustworthy. But the reality is cruel.</p><p>On my first Kotlin project, I saw an increasing number of <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-uninitialized-property-access-exception/">UninitializedPropertyAccessException</a>. Of course, you can check whether the property is initialized. But you can forget to do it, right? Or not you, your junior collegue.</p><p><strong>Be paranoid. If something can break — it will.</strong></p><p>Use nullable var instead. Example:</p><pre>var signData: SignData? = null</pre><pre>// ....</pre><pre>signData.cost?.<em>let </em><strong>{<br>    </strong>updateViewState<em>(</em>DomainViewState.DataReady<em>(</em><strong>it</strong>, domain<em>))<br></em><strong>} </strong>?: <em>run </em><strong>{<br>    </strong>Timber.e<em>(</em>Exception<em>(</em>&quot;SignData.Cost is null but it is required&quot;<em>))<br>    </em>sendMessageEvent<em>(</em>R.string.<em>domain_error)<br></em><strong>}</strong></pre><p>As you see, here you <em>have to</em> use a null check — let. As a bonus, you can use ?: operator and <em>write something to handle</em> the possible case when signData.cost will be null. Even if you <em>do not ever</em> expect it to be null but by design, technically it <em>can</em> be. Oh, and do not ever !! it.</p><h3>When construction</h3><h4>Statement or expression?</h4><p>When is a wonderful construction that makes our lives better every day. But you should be aware that in some cases when is a statement and in some — expression.</p><p>If you require to use the result of when construction, it means that it’s an expression:</p><pre>val result = when <em>(</em>event<em>) {<br>    </em>is ViewEvent.One -&gt; onOne<em>()<br>    </em>ViewEvent.Two -&gt; onTwo<em>()<br>}</em></pre><p>If you use when as an expression, the compiler checks all the possible branches. If in the above example event is nullable, the code won’t compile. You will have to change it to:</p><pre>val result = when <em>(</em>event<em>) {<br>    </em>is ViewEvent.One -&gt; onOne<em>()<br>    </em>ViewEvent.Two -&gt; onTwo<em>()<br></em>    null -&gt; { /* something */ }<br><em>}</em></pre><p>But if you do not use the result somehow, the compiler doesn’t force to handle all the possible cases:</p><pre>when <em>(</em>event<em>) {<br>    </em>is ViewEvent.One -&gt; onOne<em>()<br>    </em>ViewEvent.Two -&gt; onTwo<em>()<br>}</em></pre><p>This is a statement, the result is not used and <strong>this is the vulnerable place</strong>.</p><p>Let’s say you’re using <a href="https://medium.com/@alexzaitsev/mvi-with-android-compose-on-a-real-example-f5d522707be5">MVI</a> as a presentational pattern. Your Composable is listening ViewEvents from ViewModel.</p><p>You can write something like:</p><pre>@Composable<br>private fun EventsProcessor<em>(<br>    </em>viewModel: SplashViewModel,<br>    onOpenDomainsList: <em>() </em>-&gt; Unit,<br>    onStartWalletImport: <em>() </em>-&gt; Unit<br><em>) {<br>    </em>val event: SplashViewEvent? = viewModel.viewEvents.collectAsState<em>(</em>initial = null<em>)</em>.value<br>    when <em>(</em>event<em>) {<br>        </em>is SplashViewEvent.OpenDomainsList -&gt; onOpenDomainsList<em>()<br>        </em>SplashViewEvent.StartWalletsImport -&gt; onStartWalletImport<em>()<br>    }<br>}</em></pre><p>Do you already see the issue?</p><p>If no — answer the next question: <em>What will happen if in the future you or your colleague add new </em><em>ViewEvent?</em></p><p>The correct answer is — the code author will have to manually control it and not forget to change the above when. And that means that most probably at some moment the issue will be introduced.</p><p>Again. <strong>Be paranoid. If something can break — it will.</strong></p><p>The above code can be easily fixed just by turning the statement into an expression:</p><pre>@Composable<br>private fun EventsProcessor<em>(<br>    </em>viewModel: SplashViewModel,<br>    onOpenDomainsList: <em>() </em>-&gt; Unit,<br>    onStartWalletImport: <em>() </em>-&gt; Unit<br><em>) {<br>    </em>val event: SplashViewEvent? = viewModel.viewEvents.collectAsState<em>(</em>initial = null<em>)</em>.value<br>    return when <em>(</em>event<em>) {<br>        </em>null -&gt; <em>{<br>        }<br>        </em>is SplashViewEvent.OpenDomainsList -&gt; onOpenDomainsList<em>()<br>        </em>SplashViewEvent.StartWalletsImport -&gt; onStartWalletImport<em>()<br>    }<br>}</em></pre><p>All you have to add is return. Or assign when result to a variable. You don’t have to use it. The only purpose is to force the compiler the check. Using this approach you <em>never ever</em> forget to change when.</p><h4>Else branch</h4><p>Another way to shoot your leg is to use else branch for when. Else consumes all the cases that are not handled manually in other branches.</p><p>Do you see it? Again, imagine a case when in the future someone changes the sealed class but the compiler won’t remind you to handle a new case. Just because there is else there.</p><p>So, <strong>never ever</strong> use else branch for when. And you will be safe.</p><h3>Conclusion</h3><p>Thank you for reading, my fellow friend.</p><p>I think you got the idea: writing any line of your code keep asking a question — <strong>will it be safe if a new person comes to the project and starts writing the code? </strong>Just imagine that you will go on vacation and a junior colleague will have to fix the urgent issue while you’re absent.</p><p>And remember. <strong>Be paranoid. If something can break — it will.</strong></p><p>That’s why it’s so important to write code that is unbreakable <em>by design</em>. The code that <em>doesn’t rely on </em>your or someone else’s memory. Just because memory is a bad thing to rely on. Especially when the system is growing.</p><p>Happy coding! <strong>Follow me on </strong><a href="https://twitter.com/alexzaitsev_btc"><strong>Twitter</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83752ad4fcc3" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/follow-these-simple-kotlin-rules-to-write-unbreakable-code-and-stay-99-crash-free-83752ad4fcc3">Follow these simple Kotlin rules to write unbreakable code and stay 99+% crash-free</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling back press for modals on Android Compose]]></title>
            <link>https://proandroiddev.com/handling-back-press-on-android-compose-d345c0caea6a?source=rss-6c59eafdbea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d345c0caea6a</guid>
            <category><![CDATA[android-compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alex Zaitsev]]></dc:creator>
            <pubDate>Thu, 10 Mar 2022 09:17:09 GMT</pubDate>
            <atom:updated>2022-03-20T09:02:52.712Z</atom:updated>
            <content:encoded><![CDATA[<p>This article answers:</p><ol><li>How to handle back press for: ModalBottomSheet, AlertDialog or any other modal window.</li><li>What to do if there are several modals on the screen.</li></ol><p>The proposed approach is universal and can be applied to other similar cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*GnHm01E-TRwSykBA9JIA4Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@tylercaseyprod?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tyler Casey</a> on <a href="https://unsplash.com/s/photos/silicon-valley?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Let’s dive into it. Here is the main utility class:</p><pre><em>/**<br> * This class helps to unitize back navigation. There can be several folded BackNavElements.<br> *<br> * Each time user presses the Back button, the whole chain is asked one-by-one starting from the most child node<br> * whether any handler needs to process itself. In case it needs - it processes and returns the Result.CANNOT_GO_BACK.<br> * Whole chain do not proceed if ANY of the elements returns the Result.CANNOT_GO_BACK.<br> *<br> * So, the chain is processed only if ALL of its sub handles returned the Result.CAN_GO_BACK.<br> *<br> * This utilize the cases when user has several dialogs on the screen that needs to be closed<br> * one-by-one.<br> */<br></em>class BackNavElement private constructor<em>(<br>    </em>private var child: BackNavElement? = null,<br>    private val handler: <em>() </em>-&gt; Result<br><em>) {<br><br>    </em>enum class Result <em>{<br>        CANNOT_GO_BACK</em>,<br>        <em>CAN_GO_BACK<br>    }<br><br>    /**<br>     * Adds element to the END of the chain.<br>     */<br>    </em>fun add<em>(</em>element: BackNavElement?<em>) {<br>        </em>this.child?.<em>let </em><strong>{<br>            it</strong>.add<em>(</em>element<em>)<br>        </em><strong>} </strong>?: <em>run </em><strong>{<br>            </strong>this.child = element<br>        <strong>}<br>    </strong><em>}<br><br>    </em>fun tryGoBack<em>()</em>: Result <em>{<br>        </em>if <em>(</em>child?.tryGoBack<em>() </em>== Result.<em>CANNOT_GO_BACK) {<br>            </em>return Result.<em>CANNOT_GO_BACK<br>        }<br>        </em>return handler<em>()<br>    }<br><br>    </em>companion object <em>{<br><br>        </em>fun default<em>(</em>child: BackNavElement? = null, handler: <em>() </em>-&gt; Unit<em>) </em>=<br>            BackNavElement<em>(<br>                </em>child = child,<br>                handler = <strong>{<br>                    </strong>handler<em>()<br>                    </em>BackNavElement.Result.<em>CAN_GO_BACK<br>                </em><strong>}</strong><em>)<br><br>        </em>fun needsProcessing<em>(</em>child: BackNavElement? = null, handler: <em>() </em>-&gt; Result<em>) </em>=<br>            BackNavElement<em>(</em>child = child, handler = handler<em>)<br>    }<br>}</em></pre><p><strong>Main takeaway points:</strong></p><ol><li>BackNavElement class allows organizing a linked list of handlers.</li><li>Handler — is a callback that must return Result.</li><li>Result can be <em>CANNOT_GO_BACK </em>or<em> </em><em>CAN_GO_BACK.</em></li><li>add function adds a new element to the end of the chain.</li><li>companion object has convenient fabric methods for BackNavElement creation.</li></ol><p>Now let’s look at the example to understand how we can take advantage of it.</p><h3>Confirmation dialog</h3><p>Use case:</p><ol><li>The <strong>user</strong> is on the screen doing some editing/other important operation.</li><li>The <strong>user</strong> presses the Back button.</li><li>The <strong>app</strong> shows a confirmation dialog.</li><li>If the <strong>user</strong> confirms the exit — the <strong>app</strong> navigates back.</li><li>If the <strong>user</strong> dismisses the dialog or cancels the exit — the <strong>app</strong> hides the dialog and stays on the screen.</li></ol><p><em>ExitConfirmDialog.kt</em></p><pre>@Composable<br>fun ExitDialog<em>(</em>@StringRes bodyResId: Int, onNavIconClicked: <em>() </em>-&gt; Unit<em>)</em>: BackNavElement <em>{<br>    </em>val showDialog = rememberMutableStateOf<em>(</em>value = false<em>)<br><br>    </em>val defaultBackHandler = BackNavElement.needsProcessing <strong>{<br>        </strong>if <em>(</em>!showDialog.value<em>) {<br>            </em>showDialog.value = true<br>            BackNavElement.Result.<em>CANNOT_GO_BACK<br>        } </em>else <em>{<br>            </em>BackNavElement.Result.<em>CAN_GO_BACK<br>        }<br>    </em><strong>}<br><br>    </strong>if <em>(</em>showDialog.value<em>) {<br>        </em>DefaultAlertDialog<em>(<br>            </em>onDismiss = <strong>{ </strong>showDialog.value = false <strong>}</strong>,<br>            titleResId = R.string.<em>exit_confirmation_title</em>,<br>            bodyResId = bodyResId,<br>            positiveButtonResId = R.string.<em>confirm</em>,<br>            onPositiveClick = <strong>{<br>                </strong>showDialog.value = false<br>                onNavIconClicked<em>()<br>            </em><strong>}</strong>,<br>            negativeButtonResId = R.string.<em>cancel<br>        )<br>    }<br><br>    </em>return defaultBackHandler<br><em>}</em></pre><p>Client Composablecontent:</p><pre>val rootBackHandler = <em>ExitDialog(<br>    </em>bodyResId = R.string.<em>exit_confirmation_body</em>,<br>    onNavIconClicked = onNavIconClicked<br><em>)<br></em>DefaultBackHandler<em>(</em>rootBackHandler<em>)<br><br>// other views such as Text, Icon, etc.</em></pre><p>Here onNavIconClicked is a callback that does navController.popBackStack<em>()</em> on a higher level.</p><p><em>DefaultBackHandler</em>:</p><pre>@Composable<br>fun DefaultBackHandler<em>(</em>backNavElement: BackNavElement<em>) </em>= BackHandler <strong>{ </strong>backNavElement.tryGoBack<em>() </em><strong>}</strong></pre><p>Where BackHandler is the default Composable provided by the framework.</p><p><strong>What happens here?</strong></p><ol><li>The <strong>user</strong> presses the Back button.</li><li>The <strong>app</strong> checks if the dialog is not shown — it shows it.</li><li>If the dialog is already shown — it will be dismissed.</li></ol><p>So the only way to go back is to press theConfirm button on AlertDialog.</p><p>Let’s look at another example.</p><h3>ModalBottomSheet dialog</h3><p>Use case:</p><p>There is a ModalBottomSheet dialog on the screen. It may be hidden or shown.</p><ol><li>The <strong>user</strong> presses the Back button while the dialog is shown — dialog changes its state to hidden.</li><li>The <strong>user</strong> presses the Back button while the dialog is hidden — onNavIconClickedis invoked.</li></ol><p>To archive it the only thing that needs to be added to the client code is:</p><pre>DefaultBackHandler<em>(<br>    </em>BackNavElement.default<em>(<br>        </em>child = <em>modalBackNavElement(</em>modalState, coroutineScope<em>)</em>,<br>        handler = onNavIconClicked<br>    <em>)<br>)</em></pre><p>Where <em>modalBackNavElement() </em>is a helper method:</p><pre>@OptIn<em>(</em>ExperimentalMaterialApi::class<em>)<br></em>fun modalBackNavElement<em>(<br>    </em>state: ModalBottomSheetState,<br>    coroutineScope: CoroutineScope,<br>    callback: <em>(() </em>-&gt; Unit<em>)</em>? = null<br><em>) </em>= BackNavElement.needsProcessing <strong>{<br>    </strong>if <em>(</em>state.isVisible<em>) {<br>        </em>state.<em>hideAnd(</em>coroutineScope = coroutineScope, thenCallback = <strong>{ </strong>callback?.invoke<em>() </em><strong>}</strong><em>)<br>        </em>BackNavElement.Result.<em>CANNOT_GO_BACK<br>    } </em>else <em>{<br>        </em>BackNavElement.Result.<em>CAN_GO_BACK<br>    }<br></em><strong>}</strong></pre><p>hideAnd():</p><pre>@OptIn<em>(</em>ExperimentalMaterialApi::class<em>)<br></em>fun ModalBottomSheetState.hideAnd<em>(<br>    </em>coroutineScope: CoroutineScope,<br>    thenCallback: <em>() </em>-&gt; Unit<br><em>) {<br>    </em>coroutineScope.<em>launch </em><strong>{<br>        </strong>if <em>(</em>isVisible<em>) {<br>            </em>hide<em>()<br>            </em>thenCallback<em>()<br>        }<br>    </em><strong>}<br></strong><em>}</em></pre><p>That’s it! The next example shows how to build chains.</p><h3>Chains</h3><p>Imagine that the screen has several states. They are represented as separate Composable functions. The appropriate Composable function is shown depending on the view state.</p><p>The Composable ChildComposable2 has 2 modals. They need to be correctly handled when the user presses the Back button.</p><p>So the screen root Composable contains:</p><pre>val rootBackHandler = <em>ExitDialog(<br>    </em>bodyResId = R.string.<em>exit_confirmation_body</em>,<br>    onNavIconClicked = onNavIconClicked<br><em>)<br></em>DefaultBackHandler<em>(</em>rootBackHandler<em>)</em></pre><p>Then depending on the state ChildComposable2 may be added into the composition.</p><pre>@Composable<br>fun ChildComposable2(<em><br></em><br>    rootBackHandler: BackNavElement,<br>    <em>// other parameters</em><br><em>) {</em></pre><pre>     rootBackHandler.<em>apply </em><strong>{<br>        </strong>add<em>(modalBackNavElement(</em>addWalletModalState, coroutineScope<em>))<br>        </em>add<em>(modalBackNavElement(</em>walletsListModalState, coroutineScope<em>))</em></pre><pre>    // other views such as Text, Icon, etc.<em><br>    </em><strong>}<br>}</strong></pre><p>As you see, the only thing that is needed is to pass rootBackHandler to the child Composable. This Composable adds its handlers via add() method.</p><p>The whole chain will be processed in the next priority — walletsListModalState, addWalletModalState, rootBackHandler .</p><p>This can be scaled to any number of child Composables or modal windows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nIir7hbClSw571CugjuhjQ.gif" /><figcaption>This is an example how several modals on the same screen can be properly handled</figcaption></figure><h3>Conclusion</h3><p>Although you may think that the solution is complex actually it’s already simplified. Previously I had children instead of child in the BackNavElement class. However, with some time passed I realized that it was overkill for my app. But if you have heavy and complex screens — you may find it useful for your use cases.</p><p>I think that maybe some libraries exist to utilize all the work. If not — write a comment, perhaps I will do some.</p><p>If you know simpler (but still flexible) solutions — let me know.</p><p>Happy coding! <strong>Follow me on </strong><a href="https://twitter.com/alexzaitsev_btc"><strong>Twitter</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d345c0caea6a" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/handling-back-press-on-android-compose-d345c0caea6a">Handling back press for modals on Android Compose</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to set Default Editor Mode to Code for Composable files in Android Studio]]></title>
            <link>https://medium.com/@alexzaitsev/how-to-set-default-editing-mode-to-code-for-composable-files-in-android-studio-d5591f0bbc40?source=rss-6c59eafdbea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5591f0bbc40</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-compose]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alex Zaitsev]]></dc:creator>
            <pubDate>Thu, 24 Feb 2022 14:02:52 GMT</pubDate>
            <atom:updated>2022-03-20T09:03:35.116Z</atom:updated>
            <content:encoded><![CDATA[<p>I always preferred to write code and check on the emulator. Moreover, sometimes it’s not easy to write Preview for a complex Composable with a lot of parameters.</p><p>That’s why I find the default AS setting Default Editor Mode set to Split useless for me.</p><p>To change it, open AS preferences and type ‘split’. Change the setting to Code in front of Compose files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qP6VJVV1okpoU33DguyqTw.png" /><figcaption>Change Default Editor Mode from Split to Code in Android Studio</figcaption></figure><p>That’s it! Happy coding.<strong> Follow me on </strong><a href="https://twitter.com/alexzaitsev_btc"><strong>Twitter</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5591f0bbc40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What do you need to know before upgrading to Android Compose 1.1.0]]></title>
            <link>https://proandroiddev.com/what-do-you-need-to-know-before-upgrading-to-android-compose-1-1-0-942cf4545ac9?source=rss-6c59eafdbea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/942cf4545ac9</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-compose]]></category>
            <dc:creator><![CDATA[Alex Zaitsev]]></dc:creator>
            <pubDate>Tue, 22 Feb 2022 05:34:42 GMT</pubDate>
            <atom:updated>2022-03-20T09:04:18.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7SNtKcvY7jjtGu_pQsfOtQ.png" /><figcaption><a href="https://developer.android.com/codelabs/jetpack-compose-animation/img/ea1442f28b3c3b39.png">Source</a></figcaption></figure><p>Recently Google released a new stable <a href="https://developer.android.com/jetpack/androidx/releases/compose-foundation#1.1.0">Compose 1.1.0</a>.</p><p>I do recommend reading thoroughly the changes list. The most important you need to know:</p><ol><li>One of the most important changes is that <strong>some view elements become bigger than before </strong>(mandatory paddings were added). That means that you’ll have to go through all your screens and check if everything looks good. Be prepared for this work!<br>Most of my attention I had to pay to Checkbox and Switch views. Other views seem to look as before. (But at your project the situation may differ).</li><li>Another important change — you’ll have to<strong> bump the </strong><strong>Kotlin </strong>version to 1.6.10.</li><li>One more thing — a lot of <strong>APIs become stable</strong> and that means that you’ll have to go over your Compose code and remove unnecessary annotations (e.g. @ExperimentalAnimationApi).</li></ol><p><em>I do recommend doing the upgrade ASAP. Compose evolves fast and it’s better to jump to each next stable version than wait half a year. In that case, doing an upgrade will be a much harder job.</em></p><p>Happy coding! <strong>Follow me on </strong><a href="https://twitter.com/alexzaitsev_btc"><strong>Twitter</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=942cf4545ac9" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/what-do-you-need-to-know-before-upgrading-to-android-compose-1-1-0-942cf4545ac9">What do you need to know before upgrading to Android Compose 1.1.0</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protect your Android app content and embrace its security]]></title>
            <link>https://proandroiddev.com/protect-your-android-app-content-and-embrace-its-security-1adeb5437c6?source=rss-6c59eafdbea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1adeb5437c6</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-security]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alex Zaitsev]]></dc:creator>
            <pubDate>Tue, 08 Feb 2022 13:08:01 GMT</pubDate>
            <atom:updated>2022-03-20T09:05:40.104Z</atom:updated>
            <content:encoded><![CDATA[<p>If you develop an app that has access to secure data (e.g. finance data), it would be great to add an additional security layer. For example, protect its content visually until the user confirms their fingerprint and hide the app’s content in the Recent App menu.</p><p><a href="https://medium.com/@alexzaitsev/%D0%B2%D0%B8%D0%B7%D1%83%D0%B0%D0%BB%D1%8C%D0%BD%D0%B0%D1%8F-%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0-%D0%BA%D0%BE%D0%BD%D1%82%D0%B5%D0%BD%D1%82%D0%B0-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D1%8F-58ac546af192">Русская версия статьи.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cqucVEJJldMnR2SxuejjNg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@yangmiao?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">yang miao</a> on <a href="https://unsplash.com/s/photos/blur-phone?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The user of new iOS versions can open any more or less decent financial app and (likely) they will see that the problem is solved by blurring the content when it’s needed.</p><p>But we might have a better solution for Android. Let’s dive in!</p><h3>Content protection until the user confirms fingerprint</h3><p><strong>Usecase — user launches the app or resuming it from the background. The app needs to ask a fingerprint but show the content only when biometrics is confirmed.</strong></p><p>So, how to hide the content?</p><p>The first thing that comes into the head is to blur it.</p><p>Starting from Android 12 a new API <a href="https://blog.stylingandroid.com/rendereffect-blur/">RenderEffect</a> was added. Android Compose also got a convenient <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier#(androidx.compose.ui.Modifier).blur(androidx.compose.ui.unit.Dp,androidx.compose.ui.draw.BlurredEdgeTreatment)">blur</a> modifier. All this is good but what to do with lower APIs?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*znb_b4Wxr95Vg63E9W81mg.jpeg" /><figcaption>How blur looks on the Android 12</figcaption></figure><p>For Android 8.0+ there is a 3rd-party solution <a href="https://github.com/CameraKit/blurkit-android">blurkit</a>. Still not ideal, at first, because this is a dependency, at second, my app works with the lower Android versions.</p><p>There is one more not obvious moment with the blur itself. If behind the blur there are some movements on UI or any animation is playing — it will still be visible and this distracts.</p><p>Eventually, we decided to go with a simpler and straightforward solution — show a static view instead of blurring the content. Less code — fewer bugs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*OeYnqFmqvIffR-DanyqQJQ.jpeg" /><figcaption>Example on Xiaomi Mi 10T Pro (Android 10)</figcaption></figure><p>The code will be at the end and now let’s talk about the second problem — protect apps content in the Recent Apps.</p><h3>Protect apps content in the Recent Apps</h3><p>Naturally, I’ve started from <a href="https://stackoverflow.com/questions/43274289/android-customizing-recent-apps-thumbnail-screenshot-by-default">Stackoverflow</a>.</p><p>So what we can do:</p><ol><li>System solution <em>android:excludeFromRecents</em> — removes the app from the Recents. Possible but really bad UX. I don’t want to explain to the users where the app disappeared.</li><li>3rd-party solutions e.g. <a href="https://github.com/mguellsegarra/myopic-app-switcher"><strong>myopic-app-switcher</strong></a> that uses <a href="https://github.com/CameraKit/blurkit-android"><strong>blurkit-android</strong></a> under the hood. This option works starting from Android 8.0 and again this is a dependency. We should rely on it and trust that it will blur all the content and not crash with some bug.</li><li>System solution <em>FLAG_SECURE</em> — quite an interesting feature. User sees a white screen in the Recents + cannot make app’s screenshot (using default tools). It’s possible to allow making screenshots setting the flag in onPause and clearing it in onResume. So only Recent App feature will be left. It doesn’t work on Android 6.0 and 7.0. Only on Android 8.0.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ngMGN9lvRVaPE9k5gYHx4w.jpeg" /><figcaption>Android 8.0 (API 26)</figcaption></figure><p>4. Show custom view in onPause and hide it in onResume. Perfectly works on Android 8.0+. On lower Androids systems works differently, and the approach doesn’t work. Still a straightforward solution without dependencies and UX issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BmBnqShdnV9GbRLtofUa0A.jpeg" /><figcaption>Android 6.0 (API 23)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vG1Q-f0vFQfaXXUaYxrVcw.jpeg" /><figcaption>Android 7.0 (API 24)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0OQ1RrbCl4NG0_UtsnvwbA.jpeg" /><figcaption>Android 8.0 (API 26)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qu1wTr-KsBhcgeUidQZpxg.jpeg" /><figcaption>Android 8.0 (API 26)</figcaption></figure><p>So basically there is no solution below Android 8 (except hiding the app from Recents at all). We decided to go with №4.</p><h3>Code</h3><p><em>MainActivity.kt</em></p><pre>class MainActivity : FragmentActivity() {</pre><pre>private var recentAppsView: View? = null</pre><pre>override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        ...<br>        createRecentApppsView()<br>        addRecentAppsView()<br>    }</pre><pre>override fun onResume() {<br>        super.onResume()<br>        viewModel.checkSecurityAuth(<br>            activity = this,<br>            onSuccess = ::removeRecentAppsView,<br>            onFailure = ::finish<br>        )<br>    }</pre><pre>override fun onPause() {<br>        addRecentAppsView()<br>        super.onPause()<br>    }</pre><pre>private fun createRecentApppsView() {<br>        recentAppsView = ComposeView(this).apply { setContent { RecentApps() } }<br>    }</pre><pre>private fun addRecentAppsView() {<br>        removeRecentAppsView()<br>        recentAppsView?.let { (window.decorView as ViewGroup).addView(it) }<br>    }</pre><pre>private fun removeRecentAppsView() =<br>        recentAppsView?.let { (window.decorView as ViewGroup).removeView(it) }<br>}</pre><p><em>RecentApps.kt</em></p><pre><a href="http://twitter.com/Composable">@Composable</a><br>fun RecentApps() =<br>            Box(<br>                modifier = Modifier.fillMaxSize(),<br>                contentAlignment = Alignment.Center<br>            ) {<br>                StrictIcon(painter = painterResource(id = R.drawable.logo_light))<br>            }</pre><h3>Edge case: Xiaomi MIUI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*YyyA_v_DGXD_5CJiwHQOkg.jpeg" /><figcaption>Xiaomi Mi 10T Pro (Android 10) — installed apps are not blurred by default</figcaption></figure><p>To enable blurring user has to go to Settings and <a href="https://www.techbone.net/xiaomi/user-manual/blur-effect-in-app-preview">do it manually</a>. By default, the blur is disabled for 99% of the apps that I installed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*neyxdxijAWEIzlAQ0JDdQA.jpeg" /><figcaption>Xiaomi Mi 10T Pro (Android 10) — after blur was enabled</figcaption></figure><p>Perhaps this is not the only edge case since there are lots of firmware.</p><h3>Summary</h3><p>Hiding app content seems to be simple at the first glance but the fragmentation of Android OS makes it not an easy walk.</p><p>So ideal solution is to make minSdk = 26 (Android 8) and use any of the solutions above.</p><p>Hope that this article was useful for you.</p><p>Happy coding! <strong>Follow me on </strong><a href="https://twitter.com/alexzaitsev_btc"><strong>Twitter</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1adeb5437c6" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/protect-your-android-app-content-and-embrace-its-security-1adeb5437c6">Protect your Android app content and embrace its security</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Визуальная защита контента Android приложения]]></title>
            <link>https://medium.com/@alexzaitsev/%D0%B2%D0%B8%D0%B7%D1%83%D0%B0%D0%BB%D1%8C%D0%BD%D0%B0%D1%8F-%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0-%D0%BA%D0%BE%D0%BD%D1%82%D0%B5%D0%BD%D1%82%D0%B0-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D1%8F-58ac546af192?source=rss-6c59eafdbea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/58ac546af192</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-compose]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-security]]></category>
            <dc:creator><![CDATA[Alex Zaitsev]]></dc:creator>
            <pubDate>Fri, 04 Feb 2022 04:25:53 GMT</pubDate>
            <atom:updated>2022-02-08T13:08:39.811Z</atom:updated>
            <content:encoded><![CDATA[<p>При разработке приложения, которое имеет доступ к важным данным пользователя (например, финансовые данные), не плохо бы добавить дополнительный слой безопасности. А именно — визуально защитить контент, пока пользователь не подтвердил свой отпечаток и скрыть контент приложения из меню “Недавние приложения” (Recent Apps).</p><p><a href="https://medium.com/@alexzaitsev/protect-your-android-app-content-and-embrace-its-security-1adeb5437c6">English version of the article.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cqucVEJJldMnR2SxuejjNg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@yangmiao?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">yang miao</a> on <a href="https://unsplash.com/s/photos/blur-phone?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Пользователь новых iOS сразу же может открыть любое плюс-минус адекватное приложение для мобильного банкинга и (скорее всего) он увидит, что проблема решается добавлением размытия контента (blur) в нужные моменты.</p><p>Именно такие входящие данные я и получил для разрешения данной задачи. Сразу скажу, что требование именно блюрить контент добавило работы и по итогу мы от него отказались. Но обо всем по порядку.</p><h3>Защита контента в ожидании отпечатка пользователя</h3><p><strong>Юзкейс — пользователь запускает приложение или выводит его из фона. Нужно спросить отпечаток и показать контент только когда биометрика подтверждена.</strong></p><p>Итак, как же скрыть контент?</p><p>Первое, что приходит в голову — размыть (заблюрить) его.</p><p>Начиная с Android 12 добавилось новое API <a href="https://blog.stylingandroid.com/rendereffect-blur/">RenderEffect</a>. Android Compose тоже получил весьма удобный модификатор <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier#(androidx.compose.ui.Modifier).blur(androidx.compose.ui.unit.Dp,androidx.compose.ui.draw.BlurredEdgeTreatment)">blur</a>. Новость-то хорошая, но как насчет девайсов с меньшими API?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*znb_b4Wxr95Vg63E9W81mg.jpeg" /><figcaption>Как выглядит blur на Android 12</figcaption></figure><p>Для Android 8.0+ есть 3rd party решение <a href="https://github.com/CameraKit/blurkit-android">blurkit</a>. Все еще не идеально, во-первых, потому что это зависимость, а во-вторых, мое приложение работает и на низших версиях Андроида.</p><p>Помимо отсутствия нативных решений для младших версий Андроида, есть еще одна неочевидная особенность — если на UI, который под блюром, происходит какая-то операция или проигрывается анимация — её будет видно (хоть и плохо) и это отвлекает.</p><p>В итоге было принято решение просто показывать статичную view, что является очень прямолинейным и элегантным решением. Меньше кода — меньше багов.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*OeYnqFmqvIffR-DanyqQJQ.jpeg" /><figcaption>Пример на Xiaomi Mi 10T Pro (Android 10)</figcaption></figure><p>Код будет в конце, а пока давайте посмотрим на вторую проблему — блюрить приложение в недавних.</p><h3>Защита контента приложения в Recent Apps</h3><p>Начал я с уже проделанного сообществом труда, т.е. со <a href="https://stackoverflow.com/questions/43274289/android-customizing-recent-apps-thumbnail-screenshot-by-default">Stackoverflow</a>.</p><p>Итого, есть следующие варианты:</p><ol><li>Системное решение <em>android:excludeFromRecents</em> — скрывает приложение из недавних. Отбрасываем, т.е. ухудшает UX. Попробуй объясни потом пользователям, куда девается апка.</li><li>Сторонние решения, например <a href="https://github.com/mguellsegarra/myopic-app-switcher"><strong>myopic-app-switcher</strong></a>, который под капотом использует тот же <a href="https://github.com/CameraKit/blurkit-android"><strong>blurkit-android</strong></a>. Как вариант, но работает с Android 8.0 и, опять-таки, это зависимость, которой надо поверить, что она действительно всё заблюрит, а не упадет на каком-то баге.</li><li>Системное решение <em>FLAG_SECURE</em> — весьма интересная фича. Суть в том, что в недавних юзер видит белый экран + не может сделать скрин апки стандартными средствами. Проблему невозможности сделать скрин можно обойти, устанавливая флаг в onPause и сбрасывая в onResume, таким образом вычленим из функционала только сокрытие контента из Recent Apps. У меня не завелось на Android 6.0 и 7.0, а соотв. работает тоже с Android 8.0.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ngMGN9lvRVaPE9k5gYHx4w.jpeg" /><figcaption>Android 8.0 (API 26)</figcaption></figure><p>4. Показывать кастомную вьюху в onPause и скрывать ее в onResume. Отлично работает на Android 8.0+. На андроидах ниже система как-то по-другому делает скрин контента, который показывается в недавних, и поэтому способ не работает. Очень простое решение без зависимостей.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BmBnqShdnV9GbRLtofUa0A.jpeg" /><figcaption>Android 6.0 (API 23)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vG1Q-f0vFQfaXXUaYxrVcw.jpeg" /><figcaption>Android 7.0 (API 24)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0OQ1RrbCl4NG0_UtsnvwbA.jpeg" /><figcaption>Android 8.0 (API 26)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qu1wTr-KsBhcgeUidQZpxg.jpeg" /><figcaption>Android 11.0 (API 30)</figcaption></figure><p>Итого, решения ниже Android 8 по факту нет (кроме как совсем убрать из недавних). Мы приняли решение двигаться с вариантом №4.</p><h3>Код</h3><p><em>MainActivity.kt</em></p><pre>class MainActivity : FragmentActivity() {</pre><pre>private var recentAppsView: View? = null</pre><pre>override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        ...<br>        createRecentApppsView()<br>        addRecentAppsView()<br>    }</pre><pre>override fun onResume() {<br>        super.onResume()<br>        viewModel.checkSecurityAuth(<br>            activity = this,<br>            onSuccess = ::removeRecentAppsView,<br>            onFailure = ::finish<br>        )<br>    }</pre><pre>override fun onPause() {<br>        addRecentAppsView()<br>        super.onPause()<br>    }</pre><pre>private fun createRecentApppsView() {<br>        recentAppsView = ComposeView(this).apply { setContent { RecentApps() } }<br>    }</pre><pre>private fun addRecentAppsView() {<br>        removeRecentAppsView()<br>        recentAppsView?.let { (window.decorView as ViewGroup).addView(it) }<br>    }</pre><pre>private fun removeRecentAppsView() =<br>        recentAppsView?.let { (window.decorView as ViewGroup).removeView(it) }<br>}</pre><p><em>RecentApps.kt</em></p><pre><a href="http://twitter.com/Composable">@Composable</a><br>fun RecentApps() =<br>            Box(<br>                modifier = Modifier.fillMaxSize(),<br>                contentAlignment = Alignment.Center<br>            ) {<br>                StrictIcon(painter = painterResource(id = R.drawable.logo_light))<br>            }</pre><h3>Edge case: Xiaomi MIUI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*YyyA_v_DGXD_5CJiwHQOkg.jpeg" /><figcaption>Xiaomi Mi 10T Pro (Android 10) — устанавливаемые приложение не заблюрены по умолчанию</figcaption></figure><p>Чтобы включить размытие, пользователю надо сходить в настройки и <a href="https://www.techbone.net/xiaomi/user-manual/blur-effect-in-app-preview">сделать это руками</a>. По умолчанию размытие выключено на 99% приложений, которые я устанавливал.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*neyxdxijAWEIzlAQ0JDdQA.jpeg" /><figcaption>Xiaomi Mi 10T Pro (Android 10) — После того, как размытие было включено</figcaption></figure><p>Возможно, это не единственный edge case, ведь прошивок великое множество.</p><h3>Итого</h3><p>Внешне функция сокрытия контента кажется чем-то незамысловатым, но нужно понимать, что это безопасность пользователя, поэтому время ей уделить стоит.</p><p>Резюмируя, идеальным решением будет установить minSdk = 26 (Android 8) и использовать любое из удобный решений.</p><p>Разработка под Android никогда не была легким занятием и подобные кейсы это доказывают. Фрагментарность системы — это то, с чем Андроид разработчикам приходится жить. Надеюсь, эта статья немного облегчит нам жизнь.</p><p>Успехов!</p><p>P.S. заходите <a href="https://t.me/alexsattvablog">в мой блог</a>✌️</p><p>Эта статья <a href="https://habr.com/ru/post/649303/">на хабре</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58ac546af192" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Compose rules that will save you tons of time]]></title>
            <link>https://medium.com/@alexzaitsev/android-compose-rules-that-will-save-you-tons-of-time-6f2d0c3df418?source=rss-6c59eafdbea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f2d0c3df418</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Alex Zaitsev]]></dc:creator>
            <pubDate>Fri, 28 Jan 2022 07:23:42 GMT</pubDate>
            <atom:updated>2022-03-20T09:11:28.481Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2IjWavPYnLqdEHOkQ-w_QQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@aleskrivec?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ales Krivec</a> on <a href="https://unsplash.com/s/photos/time-saver?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>As it was mentioned in the previous article, the main challenge with MVI for the project with a growing codebase is the necessity of rules: how to name and where to store Composables.</p><p>Read the <a href="https://medium.com/@alexzaitsev/mvi-with-android-compose-on-a-real-example-f5d522707be5"><strong>first article with the practical example</strong></a> and the <a href="https://medium.com/@alexzaitsev/pros-and-cons-of-mvi-with-android-compose-67a1748dc65b"><strong>second one about the MVI with Android Compose pros and cons</strong></a>.</p><p>That’s why developers need some kind of standard: naming and code structure conventions for their Composables.</p><h3>Detekt</h3><p>First of all, I suggest you introduce <a href="https://github.com/detekt/detekt">Detekt</a> to your project. It uses <a href="https://github.com/pinterest/ktlint">ktlint</a> under the hood and already have a lot of the rules inside. Not all of them are applicable for Android Compose though. You will need to make some tuning. Ideally, you should start a new project with Detekt set up (but it’s possible to add it at any moment of time). Don’t forget to set up auto-formatting — this is <em>very</em> convenient. But this article is not about Detekt set up, you will have to deal with it on your own.</p><h3>Where to store Composables</h3><p>I suggest creating a package screen. This is a high-level package. For each screen create its own. Also, you can group them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*rwRCBEFa35rOFBtIRRZs6A.png" /><figcaption>Composables organization on a high level</figcaption></figure><p>Inside of the screen-specific package, you may stick to the next file structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*n8Lqu6ThhYzt0WmdKNkQ4A.png" /><figcaption>Files structure inside a screen-specific package</figcaption></figure><p>Also at some point in your development you may understand that you need some general folder for the Composables that are reused across different screens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*p9He4n97fQvoq7VkkPi_Cg.png" /><figcaption>How you can store your general Composables</figcaption></figure><p>That’s how I did this. I created a package composable, inside I have component and custom. component is for modified and improved versions of the standard Composables and custom — for my own <em>views</em>. If I need to create any composable that is not a <em>view</em> — I just add it to the root of composable. Like PluralResources.kt in my example.</p><h3>How to name Composables</h3><p>This rule should be introduced only if you’re going to have more than 1 file for your Composables per screen. In another case only 1 top-level Composable like ScreenOne can be public and other ones can be private inside the file. Easy!</p><p>But if you decide to have 1 ViewState — 1 file (or another similar scheme), you automatically need some naming rules.</p><p>It would be nice if Kotlin has some kind of package-level visibility modifiers. As this is not possible, you cannot have simple names for the similar states of different screens.</p><p>I mean that if Screen1 has the states Loading, DataReady, and DataError and Screen2 has the same states, you cannot name the Composables for the 1st and the 2nd screen the same. You have to distinguish them and that&#39;s why the best thing I can suggest is to add screen name as a prefix for such high-level Composables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*AmEZuEzDRsVParrID5OWzQ.png" /><figcaption>How it may look like</figcaption></figure><p>And store them in the .kt files with the same names. Each file can have lower-level private Composables to form the final publicScreen**State.</p><h3>Conclusion</h3><p>These examples are from the real-live app that works in production. If you have any questions — do not hesitate to ask.</p><p>Happy coding! <strong>Follow me on </strong><a href="https://twitter.com/alexzaitsev_btc"><strong>Twitter</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f2d0c3df418" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>