<?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 Lubos Mudrak on Medium]]></title>
        <description><![CDATA[Stories by Lubos Mudrak on Medium]]></description>
        <link>https://medium.com/@LubosMudrak?source=rss-e856388adc0e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*DJd_iO1KynOX3sEdk8j5jw.jpeg</url>
            <title>Stories by Lubos Mudrak on Medium</title>
            <link>https://medium.com/@LubosMudrak?source=rss-e856388adc0e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 20:35:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@LubosMudrak/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Testing your generated Kotlin code]]></title>
            <link>https://medium.com/@LubosMudrak/testing-your-generated-kotlin-code-e8c39217d12e?source=rss-e856388adc0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8c39217d12e</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[code-generation]]></category>
            <dc:creator><![CDATA[Lubos Mudrak]]></dc:creator>
            <pubDate>Sun, 19 Jan 2020 22:03:56 GMT</pubDate>
            <atom:updated>2020-01-19T22:03:56.828Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1fpizjL8tmnRo7-GWEbXw.jpeg" /></figure><p>I’ve always liked creating simple annotation processors. There is something satysfing to see lot’s of code being generated for you while all it takes is just providing correct annotation to correct element and Et voila! That is of course if you trust compiler to generate correct code.</p><p>To verify generated code of my annotation processors I’ve usually created a module that would provide sample on how to correctly use the processor and how to use the generated code. This kinda worked for some time, but this didn’t help with catching unwanted behavior. And what we do if we want to have all edge cases under control ? Yes, we write tests!</p><p>Writing tests for generated code is something I’ve never done, so I was really surprised that I wasn’t able to somehow easily attach generated code for source Set and just reference that in my junit test cases. Fortunately one of my colleagues referenced me a library that would help with this.</p><p><a href="https://github.com/tschuchortdev/kotlin-compile-testing">tschuchortdev/kotlin-compile-testing</a></p><h3>Enter Kotlin Compile Testing</h3><p>Kotlin Compile Testing help writing unit tests for you annotation processor and can accept both Java and Kotlin source code, if you would like to test for that.</p><p>Now for a simple example. Let’s assume that we have an <strong><em>@IntSummable</em> </strong>annotation that would generate an extensions function for annotated data class, which would sum all the integers parameters of primary constructor.</p><p>A test case to verify content of a generated file of a Foo class would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/088497ae5f5d94ca856bd7bc6a3a3aec/href">https://medium.com/media/088497ae5f5d94ca856bd7bc6a3a3aec/href</a></iframe><p><strong>Kotlin Compile Testing takes care of:</strong></p><ul><li>generating stubs</li><li>running apt</li><li>running kotlinc with generated code from previous steps</li><li>running javac with java sources and compiled Kotlin classes</li></ul><p>You can of course access all of this files as properties of the <strong>KotlinCompilation.Result</strong> object that is returned as a result of <strong>compile() </strong>function.</p><p>There is also a <strong>ClassLoader</strong> instance provided as a part of <strong>KotlinCompilation.Result</strong> that points to generated source, but I was somehow unable to properly load my class and validate presence of my extension function at runtime (I’ll leave this for a future post).</p><p>I’ve also create a small sample module which also uses <a href="https://github.com/square/kotlinpoet">KotlinPoet</a> for it’s fluent API:</p><p><a href="https://github.com/lupajz/compile-testing-sample">lupajz/compile-testing-sample</a></p><p><em>PS: Feel free to leave a note if your experience testing annotation processors is different</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8c39217d12e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[It’s not the Runnable you’re looking for]]></title>
            <link>https://medium.com/@LubosMudrak/its-not-the-runnable-you-re-looking-for-321da0fa8e97?source=rss-e856388adc0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/321da0fa8e97</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Lubos Mudrak]]></dc:creator>
            <pubDate>Fri, 03 Aug 2018 12:42:21 GMT</pubDate>
            <atom:updated>2018-08-03T14:07:42.423Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YnF7hY2ymS54iTNLuxVT8A.jpeg" /></figure><p>So, I got burned by Kotlin recently. Don’t get me wrong here, I like it that I still find myself in situations where I think things should work, but they just don’t.</p><p>Let me describe the problem here. My colleague asked if I know how one could debounce <em>LiveData</em> emissions, similar to behaviour of <a href="http://reactivex.io/documentation/operators/debounce.html">debounce operator of RxJava</a>, with a help of <em>MediatorLiveData</em> and some simple code, that just always reschedules message send to UI thread, I tried to implement it like this:</p><pre>val <strong>runnable</strong> = <strong>{<br> </strong>mediatorLiveData.<em>value </em>= source.<em>value<br></em><strong>}</strong></pre><pre>mediatorLiveData.addSource(source) <strong>{ newElement -&gt; <br> </strong>handler.removeCallbacks(<strong>runnable</strong>)<br> handler.postDelayed(<strong>runnable</strong>, delay)<br><strong>}</strong></pre><p>Seems good, code complies without any errors or warnings. But the result is nowhere near what one would expect, as the queued <em>Runnables</em> are not being dequeued and will always get executed, which is not in our desire, but rather have the <em>Runnable</em> execute only after give time if no new element was emitted by the source <em>LiveData</em>.<br>At first glance the code seems correct so the obvious step should be to take a look at decompiled bytecode using awesome Intellij tooling (<em>Tools -&gt; Kotlin -&gt; Show Kotlin Bytecode -&gt; Decompile</em>):</p><pre>class <strong>DataKt$debounce$$inlined$also$lambda$1$1</strong> implements Runnable {<br>   // $FF: synthetic field<br>   private final Function0 function;<br><br>   Livedata2Kt$debounce$$inlined$also$lambda$1$1(Function0 var1) {<br>      this.function = var1;<br>   }<br><br>   // $FF: synthetic method<br>   public final void run() { ... }<br>}</pre><pre>// $FF: synthetic field<br>final <strong>Function0</strong> $runnable;</pre><pre>public final void onChanged(@Nullable Object it) {<br>  Handler var10000 = this.$handler;<br>  <strong>Object var10001</strong> = this.$runnable;<br>  Object var2;<br>  if (this.$runnable != null) {<br>    var2 = var10001;<br>    <strong>var10001 = new DataKt$debounce$$inlined$also$lambda$1$1((Function0)var2);</strong><br>  }<br><br>  <strong>var10000.removeCallbacks((Runnable)var10001);</strong><br>  var10000 = this.$handler;<br>  var10001 = this.$runnable;<br>  if (this.$runnable != null) {<br>    var2 = var10001;<br>    <strong>var10001 = new DataKt$debounce$$inlined$also$lambda$1$2((Function0)var2);</strong><br>  }<br><br>  <strong>var10000.postDelayed((Runnable)var10001, this.$delay$inlined);</strong><br>}</pre><p>The shortened example shows what is really happening. The important part is that since both removeCallback and postDelayed methods are expecting first parameter to be of type <em>Runnable</em> Kotlin compiler wraps the lambda function into class that implements the <em>Runnable</em> contract and always creates a new instance of the wrapper class, which results in no <em>Runnable</em> being dequeued.</p><p>The solution to this problem is simple. We just have to be explicit towards compiler about what type of callback are we going to be passing, so a simple change like:</p><pre>val runnable = <strong><em>Runnable</em></strong> <strong>{<br>  </strong>mediatorLiveData.<em>value </em>= source.<em>value<br></em><strong>}</strong></pre><p>which will result into correctly generated code:</p><pre>// $FF: synthetic field<br>final <strong>Runnable</strong> $runnable;</pre><pre>public final void onChanged(@Nullable Object it) {<br>   this.$handler.removeCallbacks(this.$runnable);<br>   this.$handler.postDelayed(this.$runnable, this.$delay$inlined);<br>}</pre><p>which results in expected code.</p><p><em>TL;DR of the story is to be explicit about types of anonymous callbacks when using Kotlin with Java interop.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=321da0fa8e97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A place for BottomAppBar]]></title>
            <link>https://medium.com/@LubosMudrak/the-place-for-bottomappbar-31e0db8f70b1?source=rss-e856388adc0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/31e0db8f70b1</guid>
            <category><![CDATA[bottomappbar]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-support-library]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Lubos Mudrak]]></dc:creator>
            <pubDate>Thu, 15 Mar 2018 14:22:08 GMT</pubDate>
            <atom:updated>2018-08-07T07:13:03.546Z</atom:updated>
            <content:encoded><![CDATA[<p>Last week as Google announced release of Android P preview they also release <a href="https://developer.android.com/topic/libraries/support-library/revisions.html#28-0-0-alpha1">first alpha version</a> of new support library that includes, amongst many interesting changes, new additions to design support library. From now on the library will include new MaterialButton, MaterialCardView, layout for Chips and BottomAppBar, also I hope we’ll get <a href="https://github.com/material-components/material-components-android/blob/master/docs/components/BackLayerLayout.md">BackLayerLayout</a> in future releases.</p><p>BottomAppBar, being an extensions of <a href="https://developer.android.com/reference/android/support/v7/widget/Toolbar.html">Toolbar</a>, feels like a compromise to provide user with some actions comfortably without the need to reach for them with thumb in the Toolbar on top on devices with bigger screen.</p><p>It comes with semi-circular cutout that cradles the attached <a href="https://developer.android.com/reference/android/support/design/widget/FloatingActionButton.html">FloatingActionButton</a> with options to set <em>cradleDiameter</em>, <em>roundedCornerRadius</em> and vertical offset of our FloatingActionButton which, if set, would change the semi-circle into arc. <br>For positioning the attached FloatingActionButton we can choose one of two alignment modes <em>FAB_ALIGNMENT_MODE_CENTER or FAB_ALIGNMENT_MODE_END</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofUdXP1U0rjOXcXrcSBnVA.png" /><figcaption>Default (center) alignment</figcaption></figure><p>Setup seems to be straightforward (unless I’ve missed something obvious). Just place the the BottomAppBar and FloatingActionButton into parent CoordinatorLayout and set <em>app:layout_anchor </em>attribute of FloatingActionButton to reference id of BottomAppBar.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;android.support.design.widget.CoordinatorLayout<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    tools:context=&quot;.MainActivity&quot;&gt;<br><br>    &lt;android.support.design.bottomappbar.BottomAppBar<br>        android:id=&quot;@+id/bottom_appbar&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_gravity=&quot;bottom&quot;<br>        app:theme=&quot;@style/ThemeOverlay.AppCompat.Dark.ActionBar&quot;<br>        app:popupTheme=&quot;@style/ThemeOverlay.AppCompat.Light&quot;<br>        app:fabAttached=&quot;true&quot;<br>        app:backgroundTint=&quot;@color/colorPrimary&quot;<br>        app:fabCradleVerticalOffset=&quot;12dp&quot;&gt;<br><br>    &lt;/android.support.design.bottomappbar.BottomAppBar&gt;<br><br>    &lt;android.support.design.widget.FloatingActionButton<br>        android:id=&quot;@+id/fab&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_gravity=&quot;bottom|center_horizontal&quot;<br>        android:src=&quot;@drawable/ic_add_white_24dp&quot;<br>        app:layout_anchor=&quot;@+id/bottom_appbar&quot;/&gt;<br><br>    &lt;FrameLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;&gt;<br><br>        &lt;android.support.design.button.MaterialButton<br>            android:id=&quot;@+id/toggle_alignment&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;48dp&quot;<br>            android:layout_gravity=&quot;center&quot;<br>            android:textColor=&quot;#fff&quot;<br>            android:text=&quot;Toggle FAB alignment&quot;<br>            app:backgroundTint=&quot;@color/colorPrimary&quot;/&gt;<br><br>    &lt;/FrameLayout&gt;<br><br>&lt;/android.support.design.widget.CoordinatorLayout&gt;</pre><p>To set menu options you can provide Menu resource to your BottomAppBar in code by calling <em>BottomAppBar.replaceMenu(R.menu.xxx) </em>and to toggle the alignment I created a simple extensions function</p><pre>import kotlinx...bottom_appbar<br>import kotlinx...fab<br>import kotlinx...toggle_alignment<br>// using kotlin-android-extensions here for findViewById calls</pre><pre>class BottomAppBarActivity : AppCompatActivity() {<br><br>  override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br>    setContentView(R.layout.<em>actvity_bottom_appbar</em>)<br><br>    //setSupportActionBar(bottom_appbar) calling this breaks it!</pre><pre>    // setting the menu<br>    bottom_appbar.replaceMenu(R.menu.<em>bottom_appbar_menu</em>)</pre><pre>    toggle_alignment.setOnClickListener <strong>{<br>      </strong>bottom_appbar.<em>toggleAlignment</em>()<br>    <strong>}<br> </strong>}</pre><pre> fun BottomAppBar.toggleAlignment() {<br>   val current = <em>fabAlignmentMode<br>   fabAlignmentMode </em>= current.xor(1)<br> }</pre><pre>}</pre><p>As mentioned before, since we have two alignment modes, one can toggle between them with some nice animation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*WXDhKisBs-QAaQPz82UDJg.gif" /><figcaption>Toggling the FAB alignment</figcaption></figure><p>Some notes to takeaway:</p><ul><li>Don’t call <em>setSupportActionBar()</em> with your provided BottomAppBar as it will break it</li><li>To change the background colour you should call <em>app:backgroundTint</em> instead of <em>setBackground</em> because of internal management of background</li><li>Calling <em>setTitle</em> or <em>setSubtitle</em> will have no effect as these methods are overriden and empty</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31e0db8f70b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Either love it or you haven’t used it, yet.]]></title>
            <link>https://medium.com/@LubosMudrak/you-either-love-it-or-you-havent-used-it-yet-a55f9b866dbe?source=rss-e856388adc0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a55f9b866dbe</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Lubos Mudrak]]></dc:creator>
            <pubDate>Thu, 13 Apr 2017 15:09:58 GMT</pubDate>
            <atom:updated>2017-04-13T15:30:50.437Z</atom:updated>
            <content:encoded><![CDATA[<p>It has been some time since I was introduced to <strong>Either</strong> type by my friend (now ex-coworker). At that time I knew literally nothing about <a href="https://en.wikipedia.org/wiki/Monad_(functional_programming)">monads</a> and their role in world of functional programming, so I gave it a shot and found it to be super useful also for Android development.</p><p>In this article I presume that you at least once saw some <a href="https://kotlinlang.org/">Kotlin</a> code (I’ll be using version 1.1) and if you would like to know more about monads and how to construct them in Kotlin give look to <a href="https://medium.com/u/14e6209c1c05">Alberto Ballano</a>’s series, which I find pretty sufficient as he goes over functors, applicatives and mondas.</p><p><a href="https://hackernoon.com/kotlin-functors-applicatives-and-monads-in-pictures-part-1-3-c47a1b1ce251">Kotlin Functors, Applicatives, And Monads in Pictures. Part 1/3</a></p><p>In his article Alberto, as an example, shows Optional/Maybe monad. Now in simple words Maybe is useful only if you only care about presence of wrapped value which can be present (Some&lt;A&gt;(val value: A)) or not (None), but what if you’ll like to also care about the cause that made your Optional have value of None ? Well that’s for Either to tell you.</p><p>The Either type represents a value with two possibilities. The value can be Left or Right with respective type of value they are wrapping. My friend also learned my that by convention the Left type is used to hold error value and Right to hold correct one. So with this in mind we can create our Either like:</p><pre>sealed class Either&lt;out E, out V&gt; {<br>    data class Error&lt;out E&gt;(val error: E) : Either&lt;E, Nothing&gt;()<br>    data class Value&lt;out V&gt;(val value: V) : Either&lt;Nothing, V&gt;()<br>}</pre><p>Error is basically Left and Value is Right</p><p>Now that we have our Either class we can create some useful functions for us to easily create Either instance without always explicitly calling constructor</p><pre>fun &lt;V&gt; value(value: V): Either&lt;Nothing, V&gt; = Either.Value(value)<br>fun &lt;E&gt; error(value: E): Either&lt;E, Nothing&gt; = Either.Error(value)<br><br>fun &lt;V&gt; either(action: () -&gt; V): Either&lt;Exception, V&gt; = <br>    try { <em>value</em>(action()) } catch (e: Exception) { <em>error</em>(e) }</pre><p>So now we can do:</p><pre>val wrapped: Either&lt;Throwable, Something&gt; = <br>    either { functionThatMightThrow() }</pre><p>For our Either to be useful we would like to <strong>map</strong> and <strong>chain</strong> our Either values so we should provide some functions for this. These functions have different names in different languages/libraries, so I’ll try to provide some most common that I know:</p><ol><li>map/fmap</li></ol><pre>inline infix fun &lt;E, V, V2&gt; Either&lt;E, V&gt;<br>    .map(f: (V) -&gt; V2): Either&lt;E, V2&gt; = when(this) {<br>        is Either.Error -&gt; this<br>        is Either.Value -&gt; Either.Value(f(this.value))<br>}</pre><p>2. apply/&lt;*&gt;/ap</p><pre>infix fun &lt;E, V, V2&gt; Either&lt;E, (V) -&gt; V2&gt;<br>    .apply(f: Either&lt;E, V&gt;): Either&lt;E, V2&gt; = when(this) {<br>        is Either.Error -&gt; this<br>        is Either.Value -&gt; f.<em>map</em>(this.value)<br>}</pre><p>3. flatMap/bind/chain/liftM</p><pre>inline infix fun &lt;E, V, V2&gt; Either&lt;E, V&gt;<br>    .flatMap(f: (V) -&gt; Either&lt;E, V2&gt;): Either&lt;E, V2&gt; = when(this) {<br>        is Either.Error -&gt; this<br>        is Either.Value -&gt; f(value)<br>}</pre><p>4. mapLeft/mapError</p><pre>inline infix fun &lt;E, E2, V&gt; Either&lt;E, V&gt;<br>    .mapError(f: (E) -&gt; E2): Either&lt;E2, V&gt; = when(this) {<br>        is Either.Error -&gt; Either.Error(f(error))<br>        is Either.Value -&gt; this<br>}</pre><p>5. fold/either</p><pre>inline fun &lt;E, V, A&gt; Either&lt;E, V&gt;<br>    .fold(e: (E) -&gt; A, v: (V) -&gt; A): A = when(this) {<br>        is Either.Error -&gt; e(this.error)<br>        is Either.Value -&gt; v(this.value)<br>}</pre><p>These are some most common functions you’ll need but I’m sure you’ll find a lot more on the internet.</p><p>Now for some example. The most common thing, in my code, that returns Either are network requests. But I don’t only limit to that. I try to wrap everything that makes sense for me to propagate error value so I can deal with it later (IO, some computations, …), but for an example lets say we are dealing with some HTTP stuff.</p><p>Let us have a function defined like (I’ll use either function defined above):</p><pre>fun downloadText(): Either&lt;Exception, String&gt; <br>    = either { // process of downloading that can throw something }</pre><p>We would also like to parse our String into some object of Expected type so we can have a function that does parsing, but can also throw some custom exception in case of our String being badly formatted like:</p><pre>fun parse(input: String): Either&lt;UnparsableException, Expected&gt; =    try { <br>    value(JsonParser.parse(input)) <br>} catch (e: Exception) {<br>    error(UnparsableException(&quot;Parsing failed for $input&quot;))<br>}</pre><p>And then you’ll come to a conclusion that you don’t really need the whole content of Expected object so you’ll just take some properties of it so you could have a function like:</p><pre>fun toSmallerObject(expected: Expected): Smaller { <br>    .. magic here .. <br>}</pre><p>And finally to wire this all up you would want to print out the result of this, so we compose this thing up like:</p><pre>downloadText()<br>  .flatMap(::parse)<br>  .map(::toSmallerObject)<br>  .fold(<br>      { println(&quot;There was an error: $it !&quot;) },<br>      { println(&quot;Got my smaller object: $it !&quot;) })</pre><p>Now this was just a silly example, but you can see how we can easily compose some operations together to get the result and display it.</p><p>Also this plays pretty nice with <a href="https://github.com/ReactiveX/RxJava">RxJava</a> where if you wrap your call’s (except fold) into Observable by using something like .fromCallable { } you’ll just subscribe and get your Either into onNext from where you can continue doing what you want even in case of a Exception being present.</p><p>Just to wrap this up like Maybe Either also has it place, at least for me, when doing Android related programming and I’m really thankful for sealed classes feature in Kotlin that makes building constructs like this a breeze.</p><p>P.S:</p><ul><li>If you would like to have some out of the box solution give a look to <a href="https://github.com/MarioAriasC/funKTionale">funKTionale</a> library</li><li>If you have any questions feel free to find me on #kotlinlang Slack channel</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a55f9b866dbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous layout inflation]]></title>
            <link>https://medium.com/@LubosMudrak/asynchronous-layout-inflation-7cbca2653bf?source=rss-e856388adc0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cbca2653bf</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Lubos Mudrak]]></dc:creator>
            <pubDate>Sat, 18 Jun 2016 19:32:38 GMT</pubDate>
            <atom:updated>2016-06-18T19:32:38.162Z</atom:updated>
            <content:encoded><![CDATA[<p>With recent release of <a href="https://developer.android.com/topic/libraries/support-library/revisions.html">Android Support Library, revision 24</a> Google developers baked into v4 library a new helper class for asynchronous inflation of layouts.</p><h4>Enter AsyncLayoutInflater</h4><p>You will find use for AsyncLayoutInflater in cases when you want to inflate parts of your applications UI lazily or as an response to users interactions. This helper class will allow your UI thread to continue being responsive while heavy inflation is being performed.</p><p>To use AsyncLayoutInflater you just have to create instance of it on your applications <strong>UI thread</strong>.</p><p>Consider this part of your Activity code (I’ll be using Kotlin syntax here):</p><pre>val inflater = AsyncLayoutInflater(this)</pre><p>And now with this instance you can inflate your layout file</p><pre>inflater.inflate(resId: Int, parent: ViewGroup) </pre><p>As you can see the inflate function takes 3 parameter. First is your layout resource, second is optional view intended to be a parent of inflated hierarchy and third is a OnInflateFinishedListener, wich is a callback, that will be invoked once your layout has been inflated (in sample replaced by lambda function).</p><p>In comparsion the basic inflate function of LayoutInflater, that you would normaly use, takes boolean as a third parameter, that says whether the inflated hierarchy should be attached to the root parameter. As in our async version of inflate function there isn’t such a parameter you will most likely want to call in this way:</p><pre>inflater.inflate(resId: Int, parent: ViewGroup) <br>    <strong>{ </strong>view, resid, parent <strong>-&gt; parent.addView(view) }</strong></pre><h4>Drawbacks of using AsyncLayoutInflater</h4><p>There are of course some drawbacks here:</p><ul><li>parents function <em>generateLayoutParams()</em> has to be thread-safe</li><li>all views being constructed must not create any <em>Handler</em>s or call Looper.myLooper() function</li><li>no support for setting <em>LayoutInflater.Factory</em> nor <em>LayoutInflater.Factory2</em></li><li>no support for inflating layouts containing fragments</li></ul><p>If layout that we are trying to inflate in asynchronous way can not be constructed in this way, the inflation process will automaticaly fall back to inflation on UI thread.</p><h4>Small sample in Kotlin with use of Kotlin Android Extensions</h4><p>MainActivity</p><pre>class MainActivity : AppCompatActivity() {<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.<em>activity_main</em>)<br><br>        <em>loadFirst</em>.setOnClickListener <strong>{ <br>           </strong><em>loadAsync</em>(R.layout.<em>async</em>) <strong>{ <br>             </strong><em>second</em>.text = &quot;I am second TextView&quot; <br>           <strong>} <br>        }<br>    </strong>}<br>}<br><br>fun MainActivity.loadAsync(@LayoutRes res: Int, <br>                           action: View.() -&gt; Unit) =<br>    AsyncLayoutInflater(this).inflate(res, <em>frame</em>) <br>    <strong>{ </strong>view, resid, parent <strong>-&gt;<br>        </strong><em>with</em>(parent) <strong>{<br>            </strong>addView(view)<br>            action(view)<br>        <strong>}<br>    }</strong></pre><p>activity_main.xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;LinearLayout<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:id=&quot;@+id/frame&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:padding=&quot;@dimen/activity_vertical_margin&quot;<br>    android:orientation=&quot;vertical&quot;<br>    tools:context=&quot;com.cartoon.player.MainActivity&quot;&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/loadFirst&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;48dp&quot;<br>        android:gravity=&quot;center&quot;<br>        android:layout_marginBottom=&quot;16dp&quot;<br>        android:text=&quot;Load f async&quot;/&gt;<br><br>&lt;/LinearLayout&gt;</pre><p>async.xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;LinearLayout<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:orientation=&quot;vertical&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/first&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginBottom=&quot;16dp&quot;<br>        android:text=&quot;1&quot;/&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/second&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginBottom=&quot;16dp&quot;<br>        android:text=&quot;2&quot;/&gt;<br><br>&lt;/LinearLayout&gt;</pre><p><em>Source: mostly source code for AsyncLayoutInflater class</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cbca2653bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>