<?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 Leandro Martín Peralta on Medium]]></title>
        <description><![CDATA[Stories by Leandro Martín Peralta on Medium]]></description>
        <link>https://medium.com/@argenkiwi?source=rss-b6f2ae7fced5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2KSalIwqd3kqM4U332ClFA.jpeg</url>
            <title>Stories by Leandro Martín Peralta on Medium</title>
            <link>https://medium.com/@argenkiwi?source=rss-b6f2ae7fced5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 25 Jun 2026 15:19:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@argenkiwi/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[Keyboard Layers and Home Row Modifiers]]></title>
            <link>https://argenkiwi.medium.com/keyboard-layers-and-home-row-modifiers-5c28788df243?source=rss-b6f2ae7fced5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c28788df243</guid>
            <dc:creator><![CDATA[Leandro Martín Peralta]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 08:38:20 GMT</pubDate>
            <atom:updated>2025-03-22T17:52:57.275Z</atom:updated>
            <content:encoded><![CDATA[<h4>Fundamental patterns for an effective keyboard layout.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fuXeOQj_ROevxld6" /><figcaption>Photo by Md Mahdi on Unsplash</figcaption></figure><h3>What are keyboard layers?</h3><p>When you press the A key of your keyboard you see an ‘a’ appear on your text editor. However, if you hold one of the Shift keys and the press A, what you get is a capital ‘A’. If you hold Shift and press 2, you see ‘@’ instead.</p><p>What I have just described is the behavior of the <em>Shift Layer</em>. In essence, the Shift key activates a layer that changes the output of many other keys.</p><h3>What is a modifier?</h3><p>Shift, Control and Alt are referred to as modifier keys. This is simply because they modify the behavior of other keys. That not always means emitting a different character, as in the previous example. It can also result in a action taking place. For example, holding Control and the pressing C will commonly copy the selected text; holding Alt and then pressing Tab will allow you to change the focus to another application.</p><h3>What are home row modifiers?</h3><p>The row at the center of a keyboard, where your fingers are meant to rest, is commonly called a <em>Home Row</em>. Of course, there are no modifiers on the Home Row row of a standard keyboard, all we see are characters. We cannot replace them with modifiers because we need all characters to be able to type.</p><p>But what if we could have both? After all, there is a clear difference between how we use modifier and a character keys: we hold the former and tap the latter. For example, when we tap D, we get a ‘d’, but if we held D, then tapped M and got capital ‘M’, that would mean D behaves as Shift while held.</p><h4>Why would we want to do this?</h4><p>Having quick access to modifiers and being able to press a combination of them without having to contort our hands in an awkward way can result in improved efficiency and ergonomics, also encouraging us to learn more shortcuts and key combinations that can increase our productivity.</p><h4>How can we achieve this?</h4><p>There are many tools that can modify the behavior of a key to achieve this to some extent. However, there are a few important gotchas to bear in mind:</p><ul><li>If you are typing and roll a key, meaning that you press a key before releasing the previous one, you may accidentally activate a modifies (e.g., roll from D to M and get ‘aMire’ instead of ‘admire’).</li><li>To determine whether you intend to press or hold a key, we need to wait untill either the key is released or another key is pressed. That means we won’t immediately see the characters we intend to type and we will perceive a delay or lag that can be distracting.</li></ul><p>Unfortunately, many of the Home Row Modifier (HRM) implementations you may find out there do not address these problems effectively. But worry not, there are some excellent free and open source tools that can do this properly and you can use them right now. We’ll get to that soon.</p><h3>Custom Layers</h3><p>We now know we can use HRMs to access layers, like Shift and AltGr, without moving our hands away from the center of the keyboard. What if we could have other layers that would allow us to reach, for example, Escape or the arrow keys without moving our hands? The same tools used to implement HRMs can also help with that.</p><p>The main types of custom layers you may want to consider are:</p><ul><li>Navigation/editing (also known as Extend)</li><li>Functions, numbers and symbols.</li></ul><h3>Layered Keyboard Layouts</h3><p>Putting all of these together you get a layered keyboard layout. You can find many samples on keymapdb.com, including <a href="https://github.com/argenkiwi/kenkyo">Kenkyo</a>, the layout I put together during my journey learning all the concepts discussed in this article. There you will find examples on how to properly implement HRMs, using software like <a href="https://github.com/jtroo/kanata">Kanata</a> and <a href="https://github.com/rvaiya/keyd">keyd</a>, as well as opinionated implementations of the aforementioned custom layers, which you can use as is or as inspiration for your own layers.</p><p>I hope you have found this article useful. Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c28788df243" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How many keys does your keyboard actually need?]]></title>
            <link>https://argenkiwi.medium.com/how-many-keys-does-your-keyboard-actually-need-6eeda67025f6?source=rss-b6f2ae7fced5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6eeda67025f6</guid>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[keyboard-layout]]></category>
            <dc:creator><![CDATA[Leandro Martín Peralta]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 20:45:04 GMT</pubDate>
            <atom:updated>2025-03-20T17:53:02.412Z</atom:updated>
            <content:encoded><![CDATA[<h4>TL;DR: 31.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pm9Plb7Mvkx1Tw4G" /><figcaption>Photo by Sofya on Unsplash</figcaption></figure><h4>What?</h4><p>10 keys for each of the 3 rows at the center of the keyboard plus a space-bar (or thumb key) is all you need, which makes it 31 keys.</p><h4>How?</h4><p>By using a couple of patterns, namely <em>Home Row Modifiers</em> (done properly) and <em>SpaceFN,</em> as well as a couple of layers: <em>Extend </em>(navigation and editing) and <em>Fumbol</em> (functions, numbers and symbols).</p><h4>Why?</h4><ul><li>So you can touch-type all keys, not just letters and basic symbols;</li><li>So you don’t have to move your hands much and can make better use of your stronger fingers;</li><li>So you can transition to a split, column-staggered, ergonomic, 34-key keyboard (or anything in between) and still be able to use your laptop’s keyboard with ease while remaining productive.</li></ul><h4>Interested?</h4><p>Check out the <a href="https://github.com/argenkiwi/kenkyo">Kenkyo keyboard layout</a>.</p><h3>Long version</h3><p>I have earned a living as a software developer for 15 years and have used computers, and therefore keyboards, for about 30. But I had never questioned the design and format of keyboards until the pandemic hit. It was a time of introspection and learning. This is the story of how I have used the knowledge I gradually acquired since then to put together my 31-key, layered keyboard layout: <a href="https://github.com/argenkiwi/kenkyo">Kenkyo</a>.</p><h4>The Extend Layer</h4><p>I came across it while looking at <a href="https://dreymar.colemak.org/">DreymaR’s Big Bag of Tricks</a> a few yeas back. That was the first time I heard about layers. I thought it was a great concept, but I did not try it straight away. It was after learning about <a href="https://github.com/kmonad/kmonad">kmonad</a> that I remembered it and attemped to implement my own variant for the first time. Following the <a href="https://colemakmods.github.io/ergonomic-mods/extend.html">Colemak community’s guidelines</a>, I chose to bind it to the CapsLock key.</p><p>My Extend layer has gone through many changes, but I have found it so intuitive and useful that it has never crossed my mind to let go of it.</p><h4>The Fumbol layer</h4><p>Once you learn about layers, one of the first things many of us think about is making one that can host keys like functions, numbers and symbols. I know because I have found online all sorts of creative takes on that same problem. I decided early on I just wanted to keep it simple and intuitive:</p><ul><li>The top row would contain the function keys;</li><li>the home row would become a number row;</li><li>and the bottom row would host other symbol keys that were hard to reach… and some media keys just because there was some spare room.</li></ul><p>I also wanted to be able to stay on the layer temporarily in order to type sequences of numbers, and sometimes symbols. It became clear that I had to bind it to the only proper thumb key available on a standard keyboard: the space-bar. I later learnt this pattern was once known as <a href="https://kbd.news/The-SpaceFN-concept-2315.html"><em>SpaceFN</em></a>. But it turns out it is not a trivial pattern to implement and presents similar challenges to those of the pattern we will discuss next.</p><h4>Home Row Modifiers</h4><p>As the name implies, home row modifiers (or HRMs) put keys like Ctrl, Shift and Alt/Option on the home or center row of the keyboard. They achieve this by distinguishing between taps and holds, which would result on a character being emitted or a modifier being activated respectively.</p><p>Sounds easy? Well, it’s not. Many of us are faced with a daunting sense of frustration when we try to put them in practice for the first time and abandon them early on. Unfortunately, the are many barely usable implementations out there that have given HRMs a bad reputation. But if done properly, HRMs can become an essential tool. It took me a while to figure out what makes a good implementation:</p><ul><li><strong>Prior idle time:</strong> make sure you HRMs are skipped if a key or sequence of them has been pressed recently. This is how you can <strong>avoid misfires</strong> while you are in the middle of typing. This will also drastically <strong>reduce the perceived lag</strong> when you are typing as no evaluations are taking place and the key codes are emitted immediately. Good keyboard customization tools can do this: kanata with <em>switch</em> and key timings; keyd with <em>overloadi</em>; ZMK with <em>require-prior-idle-ms</em>; and finally, as I found out on the day I’m typing this, QMK with the <a href="https://github.com/getreuer/qmk-modules/tree/main/tap_flow">Tap Flow</a> module.</li><li><strong>Trigger on release:</strong> another technique that can also <strong>prevent misfires caused by key-rolls</strong> is to only activate an HRM if the modified key is both pressed and released before the HRM itself is released.</li></ul><p>There are other interesting techniques, like Bilateral Combinations, but I believe that applying the precautions explained above and adjusting the timings to suit the typing style and speed of the user are sufficient to minimize frustrations and rip most of the benefits of HRMs.</p><h4>31 keys</h4><p>I went through many iterations to integrate the patterns described above into my layout. I only managed to reduce the number of keys to 31 after I realized I did not really need to make the <em>CapsLock</em> key useful. Many will passionately tell you how it is in a privileged location and it does not deserve it. However, if you turn it into something too useful instead, it will be your pinky finger who will suffer.</p><p>Therefore, I decided to try binding the <em>Extend</em> layer to the space-bar. After all, I knew it was the layer I use the most. But how could I access the <em>Fumbol</em> layer quickly and easily when I needed to?</p><p>As I had now plenty of unassigned keys on the left side of the Extend layer now (my pinky had been stuck on <em>CapsLock</em> so I could not reach them in the previous arrangement), I used one to swap the <em>Extend</em> layer for the <em>Fumbol</em> layer until I released the space-bar. This was great for when I needed to stay on <em>Fumbol</em> to type a series of numbers and/or symbols, but it felt like too much work when I just wanted to enter a single symbol or press a function key.</p><p>Then I remembered a technique some use to cope with their frustration with HRMs: <em>Bottom Row Modifiers</em> (BRMs). After some trial an error, I placed a pair of <em>Fumbol Layer Modifiers</em> on the V and M keys of the bottom row. While I was at it, I added an <em>AltGr</em> and a redundant <em>Ctrl</em> modifiers as well, which permitted me to perform all sorts of key combinations not only on the main layer, but on the <em>Fumbol</em> layer as well.</p><p>And that is how <em>Kenkyo</em> ended up only requiring 31 keys to do it all.</p><h4>Conclusion</h4><p>There is something about being able to rely solely on motor memory that makes typing pleasurable.</p><p>I used to think that using a tiny keyboard was an extravagant thing to do and wasn’t really practical. But I can now see that, if done right, most of the things one may do with a traditional keyboard can be done more efficiently and comfortably with a proper layout and way fewer keys.</p><p>I have recently acquired my first 36-key keyboard and transitioning to it using Kenkyo couldn’t have been easier. My new keyboard supports QMK, but I can’t find the motivation to go through the learning process that would lead me to replicate my layout using firmware because, even if I get it right (which is not certain), I won’t be able to make use of it with my laptop’s keyboard.</p><p>I hope some of you find this interesting and useful. Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eeda67025f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keyboard layer pinning]]></title>
            <link>https://argenkiwi.medium.com/keyboard-layer-pinning-20aafede96e5?source=rss-b6f2ae7fced5------2</link>
            <guid isPermaLink="false">https://medium.com/p/20aafede96e5</guid>
            <category><![CDATA[keyboard-layout]]></category>
            <category><![CDATA[keyboard-shortcuts]]></category>
            <category><![CDATA[keyboard]]></category>
            <dc:creator><![CDATA[Leandro Martín Peralta]]></dc:creator>
            <pubDate>Fri, 10 May 2024 23:42:14 GMT</pubDate>
            <atom:updated>2024-12-24T20:33:21.997Z</atom:updated>
            <content:encoded><![CDATA[<h4>Ergonomic typing using software</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*piElDeTrJnr7QfJBPnimBg.jpeg" /><figcaption>The space-bar, one of a kind</figcaption></figure><p>Imagine you are about to type the acronym <em>UNRWA</em> on a physical keyboard:</p><ol><li>You hold the <em>shift</em> key with the pinky finger of your left hand</li><li>Press <em>U</em> and <em>N</em> using your right hand</li><li>Wish you had activated <em>caps-lock</em></li><li>Proceed to awkwardly stretch the fingers of your left hand to type <em>R</em>, <em>W</em> and <em>A</em> while struggling to still hold the <em>shift</em> key</li></ol><p>Now think of the same scenario, but this time the <em>shift</em> key has swapped places with the <em>space-bar</em>:</p><ol><li>You hold the <em>shift-bar</em> with one or both of your thumbs</li><li>Type the letters with the fingers of both hands</li><li>Release the <em>shift-bar</em> and live a happy life</li></ol><p>Isn’t that great? Well, except that now, to enter a space before each word, you have to constantly slide your pinkies outwards like you were a DJ or a percussionist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ubXVAVQi-GYIxkDs" /><figcaption>Big round shift/space keys.</figcaption></figure><p>Now, what if your <em>space-bar</em> could do both?</p><ul><li>When you press it, you get a space, as usual</li><li>When you hold it, it acts as a <em>shift</em> key</li></ul><p>That would solve the problem, right? Yes, although I would not recommend replacing your shift keys with it but rather have it as an available alternative. There are many pieces of software (e.g., <a href="https://github.com/rvaiya/keyd">keyd</a>, <a href="https://github.com/jtroo/kanata/discussions/1034#discussioncomment-9428721">Kanata</a>, <a href="https://github.com/kmonad/kmonad">KMonad</a>, <a href="https://karabiner-elements.pqrs.org/">Karabiner Elements</a>, etc.) that allow you to achieve this behavior on all major operating systems. But let’s go a bit further.</p><p>In technical terms, the <em>shift</em> key activates a <strong>keyboard layer</strong> in which letters become capitalized and symbols change into other symbols. Although a seemingly useful feature, once you realize you can create your own personalized layers using the aforementioned software, you may decide that you don’t want to use your <em>space-bar</em> just as a glorified <em>shift</em> key.</p><p>You see, the <em>space-bar</em> has some very unique and important characteristics. It’s the only key designed to be:</p><ol><li>Pressed by your thumbs <strong>and</strong></li><li>Accessed by either of your hands.</li></ol><p>Your thumb is also a special kind of “finger”, so much so that it is believed opposable thumbs gave us a crucial evolutionary advantage leading to us becoming the dominant species on the planet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cymr7DhWPGvrd3Ft" /><figcaption>The thumb, a force of nature.</figcaption></figure><p>In regards to typing, the most interesting advantage of using your thumb to hold the <em>space-bar</em> is that, while doing so, your fingers are still able to reach the rest of the keyboard with relative ease.</p><p>Going back to our original example, picture the following sequence:</p><ol><li>Hold a <em>shift</em> key</li><li>Hold the <em>space-bar 📌</em></li><li>Release the <em>shift</em> key</li><li>Type the acronym</li><li>Release the <em>space-bar</em></li></ol><p>When you hold the <em>shift</em> key (1), the <em>shift</em> layer is activated, as usual, but with a particular difference: while active, holding the space-bar (2) effectively <strong>pins the shift layer</strong>. After you lift your pinky (3), <em>shift</em> remains active while you continue to type (4). Releasing the space bar (5) unpins the layer deactivating <em>shift</em>.</p><p>I call this technique <em>keyboard layer pinning</em> (or <em>anchoring</em>). I personally use it with <a href="https://github.com/argenkiwi/kenkyo">my layers</a> which enables me, for example, to pin one of them (e.g., functions, numbers, symbols) and then activate another one on top (e.g., shift, shortcuts) by holding a different key.</p><p>I have been a PC user for about 30 years now and a software developer for around half that time and I wish I had access to these tools a long time ago. I hope you find this approach as useful and impactful as I did when designing the keyboard layout that suits you best.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20aafede96e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revisiting unidirectional data flows on Android with Kotlin’s SharedFlow and StateFlow]]></title>
            <link>https://argenkiwi.medium.com/revisiting-unidirectional-data-flows-on-android-with-kotlins-sharedflow-and-stateflow-92fb74e17983?source=rss-b6f2ae7fced5------2</link>
            <guid isPermaLink="false">https://medium.com/p/92fb74e17983</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Leandro Martín Peralta]]></dc:creator>
            <pubDate>Fri, 09 Apr 2021 04:43:54 GMT</pubDate>
            <atom:updated>2021-04-11T19:24:39.619Z</atom:updated>
            <content:encoded><![CDATA[<p>I was glad to hear that <em>Kotlin </em>now has support for <em>hot flows</em> or, in the words of the <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-state-flow/">official documentation</a>:</p><blockquote>(…) [a flow whose] active instance exists independently of the presence of collectors (…)</blockquote><p>For those of us coming from the world of Reactive Streams (<em>RxJava </em>in my case), these would be the equivalent to <a href="https://rxjava-doc.readthedocs.io/en/latest/What&#39;s-different-in-2.0/#subjects-and-processors"><em>Subjects </em>and <em>Processors</em></a>.</p><p>The reason I am glad we have hot flows, in the form of <em>SharedFlow</em> and <em>StateFlow</em>, is that I can replicate <a href="https://medium.com/@argenkiwi/the-model-in-mvvm-7fef986a1894">my previous implementation of uni-directional data flow with <em>RxJava</em></a> using coroutines and flows instead.</p><h3>Let’s code</h3><p>To demonstrate my approach I will use the same example I used for the <em>RxJava </em>version of this solution. However, I will introduce some improvements to how the <em>model</em> for this application will be defined.</p><p>The <em>Event</em> and <em>State</em> definitions will stay the same:</p><pre><strong>sealed class </strong>CoinTosserEvent {<br>    <strong>object </strong>Toss : CoinTosserEvent()<br>    <strong>object </strong>Heads : CoinTosserEvent()<br>    <strong>object </strong>Tails : CoinTosserEvent()<br>}</pre><pre><strong>data class </strong>CoinTosserState(<br>        <strong>val isTossing</strong>: Boolean = <strong>false</strong>,<br>        <strong>val isHeads</strong>: Boolean = <strong>false<br></strong>)</pre><p>But instead of using a <em>Reducer</em> class I will simply use a function:</p><pre><strong>fun </strong>reduce(<br>        state: CoinTosserState,<br>        event: CoinTosserEvent<br>) = <strong>when </strong>(event) {<br>    CoinTosserEvent.Toss -&gt; state.copy(<br>            isTossing = <strong>true<br>    </strong>)<br>    CoinTosserEvent.Heads -&gt; state.copy(<br>            isTossing = <strong>false</strong>,<br>            isHeads = <strong>true<br>    </strong>)<br>    CoinTosserEvent.Tails -&gt; state.copy(<br>            isTossing = <strong>false</strong>,<br>            isHeads = <strong>false<br>    </strong>)<br>}</pre><p>And finally, I will introduce a new concept to handle side-effects. Enter the <em>Reactor</em>:</p><pre><strong>class </strong>CoinTosserReactor() {<br><br>    <strong>suspend fun </strong>react(<br>            event: CoinTosserEvent<br>    ): CoinTosserEvent? = <strong>when </strong>(event) {<br>        <strong>is </strong>CoinTosserEvent.Toss -&gt; {<br>            delay(1000)<br>            <strong>when </strong>{<br>                Math.random() &lt; .5 -&gt; CoinTosserEvent.Heads<br>                <strong>else </strong>-&gt; CoinTosserEvent.Tails<br>            }<br>        }<br>        <strong>else </strong>-&gt; <strong>null<br>    </strong>}<br>}</pre><p>I chose the term <em>Reactor</em> for this component to evoke the phrase “every action has a reaction”. The <em>react</em> method takes and <em>Event</em> and may or may not produce an <em>Event</em> in return.</p><p>In essence, here we can declare all our side-effects (e.g., network requests, database queries). If an <em>Event</em> produces no side-effects or if it is of no consequence to the logic of our application (e.g., logging), we just return a <em>null</em> value. Why am I not using a pure function for this as well? Because it is very likely I will need other dependencies for my side effects, like repositories or interactors.</p><h3>StateFlow and SharedFlow</h3><p>Now let’s get to the core of this solution and re-implement the <em>ViewModel</em> for our example app:</p><pre><strong>class </strong>CoinTosserViewModel : ViewModel() {<br><br>    <strong>private val events </strong>= <em>MutableSharedFlow</em>&lt;CoinTosserEvent&gt;()<br>    <strong>private val state </strong>= <em>MutableStateFlow</em>(CoinTosserState())<br><br>    <strong>val liveState</strong>: LiveData&lt;CoinTosserState&gt; = <strong>state</strong>.<em>asLiveData</em>()<br><br>    <strong>private val reactor </strong>= CoinTosserReactor()<br><br>    <strong>init </strong>{<br><br>        <em>viewModelScope</em>.<em>launch </em><strong>{<br><br>            </strong><em>launch </em><strong>{<br>                events</strong>.<em>mapNotNull</em>(<strong>reactor</strong>::react)<br>                        .collect <strong>{ </strong><em>launch </em><strong>{ events</strong>.emit(<strong>it</strong>) <strong>} }<br>            }<br><br>            </strong><em>launch </em><strong>{<br>                events</strong>.<em>map </em><strong>{ </strong><em>reduce</em>(<strong>state</strong>.<strong>value</strong>, <strong>it</strong>) <strong>}<br>                        </strong>.collect(<strong>state</strong>::emit)<br>            <strong>}<br>        }<br>    </strong>}<br><br>    <strong>fun </strong>onToss() {<br>        <em>viewModelScope</em>.<em>launch </em><strong>{ events</strong>.emit(CoinTosserEvent.Toss) <strong>}<br>    </strong>}<br>}</pre><p>At the top we have defined our streams of events and states. Next we expose the state to the view as <em>LiveData</em> and instantiate our reactor.</p><p>Now, what is happening inside the <em>init </em>block? We are basically doing 2 things:</p><p>First, we start collecting the events, mapping the non-null values through our reactor. If our reactor produces and event (i.e.: Heads or Tails in this example), we emit that event back into the event stream. Basically, side-effects are now being handled. Notice we launch a new coroutine to emit an event back into the same flow (not doing so would cause issues).</p><p>Second, we start collecting changes to our state by mapping new events through our reduce function and emitting the resulting state back into the state flow.</p><p>Finally, we have a public method which emits Toss events into the events flow. And that is it!</p><h3>Conclusion</h3><p>I hope this example helps you structure your applications making use of coroutines and flows. I am still refining the approach, so please get comfortable with it before using it in production. I am sure you will find ways to improve on it and adapt it to your own coding style.</p><p>You can find the source code for the example <a href="https://github.com/argenkiwi/coin-tosser/tree/flow">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92fb74e17983" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Model in MVVM]]></title>
            <link>https://argenkiwi.medium.com/the-model-in-mvvm-7fef986a1894?source=rss-b6f2ae7fced5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fef986a1894</guid>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[livedata]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Leandro Martín Peralta]]></dc:creator>
            <pubDate>Thu, 22 Mar 2018 19:24:05 GMT</pubDate>
            <atom:updated>2018-03-26T20:03:00.463Z</atom:updated>
            <content:encoded><![CDATA[<h4>State, Events and Side-Effects</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0R72oZchQ8GAEQb-LbB-Yw.jpeg" /></figure><p>I have often had the feeling it was not clear to me what the Model was in my apps. While applying the Model-View-Presenter pattern, I implemented View<em> </em>interfaces and Presenter<em> </em>classes, but there was no explicit Model<em> </em>in my code.</p><p>A while ago, I took a break from <em>Android</em> development and decided to learn <em>React</em> and <em>CycleJS</em>. It took me some time to get my head around these different ways of structuring front-end applications.</p><p>A few months later, back in the <em>Android </em>realm, I started looking into the new ViewModel<em> </em>and LiveData<em> </em>classes of the <em>Architecture Components</em> library. I decided to put in practice the concepts I had learnt by using the aforementioned <em>Javascript</em> libraries: I would represent the <strong>Model</strong> in my <em>Android</em> apps as a <strong>State</strong>,<strong> Events </strong>and<strong> Side-Effects</strong>.</p><h4>The State</h4><p>What is the State? The dictionary says it is “the particular condition that (…) something is in at a specific time”. For our purposes, that “something” will be the View<em>.</em></p><h4>Events</h4><p>What is an Event? Again, the dictionary says it is “a thing that happens or takes place”. I would add that, in the context of an application, an Event<em> </em>has the potential to change or modify the State.</p><h4>Side-Effects</h4><p>According to the dictionary definition, a Side-Effect is “ a secondary, typically undesirable effect of a drug or medical treatment”… Well, I guess the dictionary definition will not help us this time.</p><p>A Side-Effect, in the context of our Model, is something that happens as a consequence of an Event. For example, in the Event<em> </em>of a user pressing a button, a Side-Effect could be the execution of a network request or database query. These Side-Effects could produce a result in the form of an Event (e.g.: Success, Error, etc.).</p><h3>Show me the code!</h3><p>In a <a href="https://medium.com/@argenkiwi/reactive-android-apps-with-kotlin-viewmodel-livedata-and-rxjava-7cb17bcf2e9e">previous article</a> I provided a very basic example on how to represent streams of State and Events in the context of a ViewModel using <em>RxJava</em>.</p><p>As a consequence of spending time applying the approach and refining it, I wrote a very small <em>Android </em>library called <a href="https://github.com/argenkiwi/rxmodel"><em>RxModel</em></a><em>. </em>It is so small you may as well copy and paste the code into your project. In this article I will provide an example of how to use it to structure the Model in your apps.</p><h4>Coin Tosser</h4><p>For this example, we are going to build an application consisting of a screen with a TextView and a <em>Toss</em> Button . When the Button is pressed, it becomes disabled and the TextView reads “Tossing…”<em> </em>for a second. After that, the Button is re-enabled and the TextView reads either “Heads”<em> </em>or “Tails”.</p><p>I made a <a href="https://github.com/argenkiwi/coin-tosser">GitHub repository</a> with the implementation of the following example, in case you would like to check it out.</p><p>Let’s begin by modeling the Events for this use-case:</p><pre><strong>sealed class </strong>CoinTosserEvent {<br>    <strong>object </strong>Toss : CoinTosserEvent()<br>    <strong>object </strong>Heads : CoinTosserEvent()<br>    <strong>object </strong>Tails : CoinTosserEvent()<br>}</pre><p>I have used a sealed class to define 3 types of Events. This way I ensure the application is only going to expect a finite set of Event types.</p><p>Next, we will represent the State for the same use-case:</p><pre><strong>data class </strong>CoinTosserState(<br>        <strong>val isTossing</strong>: Boolean = <strong>false</strong>,<br>        <strong>val isHeads</strong>: Boolean = <strong>false<br></strong>)</pre><p>I used a data class to represent the different properties of the State. The State is immutable: you cannot modify its properties. But how are we going to update the State after an Event occurs? We will we make a copy of the State and change only the properties we need to change (data classes count with a very handy copy(...) method that makes this easy).</p><p>Which takes us to the following step: defining a Reducer (if you haven’t already, you will need to add <a href="https://github.com/argenkiwi/rxmodel"><em>RxModel</em></a> to your project to move forward).</p><pre><strong>object </strong>CoinTosserReducer : Reducer&lt;CoinTosserState, CoinTosserEvent&gt; {<br>    <strong>override fun </strong>apply(<br>            state: CoinTosserState,<br>            event: CoinTosserEvent<br>    ) = <strong>when </strong>(event) {<br>        CoinTosserEvent.Toss -&gt; state.copy(<br>                isTossing = <strong>true<br>        </strong>)<br>        CoinTosserEvent.Heads -&gt; state.copy(<br>                isTossing = <strong>false</strong>, <br>                isHeads = <strong>true<br>        </strong>)<br>        CoinTosserEvent.Tails -&gt; state.copy(<br>                isTossing = <strong>false</strong>, <br>                isHeads = <strong>false<br>        </strong>)<br>    }<br>}</pre><p>The Reducer consists of an object with a single function which takes the current State and an incoming Event and returns a new updated State.</p><p>So far we expressed what the Model of our app is in a declarative manner. But I purposely introduced a requirement in the specification of the use-case:</p><blockquote>When the Button is pressed, it becomes disabled and the TextView reads “<em>Tossing…” </em><strong>for a second</strong>.</blockquote><p>What the statement above implies is that some work is going to be done in the background for some time and it will eventually produce a result. We are now dealing with asynchrony, which is what <em>RxJava</em> is meant to help us with. Triggering this asynchronous work is what I call a Side-Effect.</p><p>Let’s define a concrete Model and declare its Side-Effects:</p><pre><strong>class </strong>CoinTosserModel<br>    : StateEventModel&lt;CoinTosserState, CoinTosserEvent&gt;(<br>        CoinTosserState(),<br>        CoinTosserReducer<br>) {<br>    <strong>private val tossEventsObservable </strong>= <strong>eventObservable<br>            </strong>.ofType(CoinTosserEvent.Toss::<strong>class</strong>.<em>java</em>)<br><br>    <strong>private val tossSideEffect </strong>= Single<br>            .timer(1, TimeUnit.<strong>SECONDS</strong>)<br>            .map <strong>{<br>                when </strong>{<br>                    Math.random() &lt; .5 -&gt; CoinTosserEvent.Heads<br>                    <strong>else </strong>-&gt; CoinTosserEvent.Tails<br>                }<br>            <strong>}<br><br>    override fun </strong>subscribe() = publish(<br>            <strong>tossEventsObservable</strong>.flatMapSingle <strong>{ tossSideEffect }<br>    </strong>)<br>}</pre><p>Notice CoinTosserModel extends from StateEventModel, which takes the initial State of the View and a Reducer as its constructor’s parameters.</p><p>And now I will explain what is probably the most complex part of this article: binding Events to Side-Effects and Side-Effects to Events.</p><ul><li>The first thing we do is obtaining an Observable of a specific Event type (Toss in this case).</li><li>Then, we define the Side-Effect to be triggered by that Event type and make sure its possible results are mapped to Events (Heads or Tails in this case).</li><li>Finally, we bind the Event to the Side-Effect and publish the resulting Event back into the Event stream.</li></ul><p>The definition of our Model is complete. We can now use it in our ViewModel:</p><pre><strong>class </strong>CoinTosserViewModel : ViewModel() {<br>    <strong>private val model </strong>= CoinTosserModel()<br>    <strong>private val disposable </strong>= <strong>model</strong>.subscribe()<br><br>    <strong>val liveState</strong>: LiveData&lt;CoinTosserState&gt; =<br>            LiveDataReactiveStreams.fromPublisher(<br>                <strong>model</strong>.<strong>stateObservable</strong>.toFlowable(<br>                    BackpressureStrategy.<strong>LATEST<br>                </strong>)<br>            )<br><br>    <strong>override fun </strong>onCleared() {<br>        <strong>super</strong>.onCleared()<br>        <strong>disposable</strong>.dispose()<br>    }<br><br>    <strong>fun </strong>onToss() {<br>        <strong>model</strong>.publish(CoinTosserEvent.Toss)<br>    }<br>}</pre><p>We expose the State to the View as LiveData so we do not have to deal with the intricacies of the Activity (or Fragment) life-cycle. We subscribe to the Model and dispose of the subscription when the ViewModel is cleared to avoid leaks that could be produced by ongoing asynchronous work related to the Side-Effects we trigger.</p><p>The onToss() method will be called by the View as you can see below:</p><pre><strong>class </strong>CoinTosserActivity : AppCompatActivity() {<br><br>    <strong>override fun </strong>onCreate(savedInstanceState: Bundle?) {<br>        <strong>super</strong>.onCreate(savedInstanceState)<br>        setContentView(R.layout.<em>activity_coin_tosser</em>)<br><br>        <strong>val </strong>viewModel = ViewModelProviders.of(<strong>this</strong>)<br>            .get(CoinTosserViewModel::<strong>class</strong>.<em>java</em>)</pre><pre>        viewModel.<strong>liveState</strong>.observe(<strong>this</strong>, <em>Observer </em><strong>{<br>            it</strong>?.<em>apply </em><strong>{<br>                </strong>statusTextView.<em>text </em>= <strong>when</strong>{<br>                    <strong>isTossing </strong>-&gt; getString(R.string.<em>tossing</em>)<br>                    <strong>isHeads </strong>-&gt; getString(R.string.<em>heads</em>)<br>                    <strong>else </strong>-&gt; getString(R.string.<em>tails</em>)<br>                }<br>                tossButton.<em>isEnabled </em>= !<strong>isTossing<br>            }<br>        }</strong>)<br><br>        tossButton.setOnClickListener <strong>{ </strong>viewModel.onToss() <strong>}<br>    </strong>}<br>}</pre><p>The View observes the State and updates accordingly. When the <em>Toss</em> button is clicked, it lets the ViewModel know.</p><p>That’s it! The cycle is complete. I hope this approach opens up more possibilities to what you can achieve in your apps. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fef986a1894" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive Android Apps with Kotlin, ViewModel, LiveData and RxJava]]></title>
            <link>https://argenkiwi.medium.com/reactive-android-apps-with-kotlin-viewmodel-livedata-and-rxjava-7cb17bcf2e9e?source=rss-b6f2ae7fced5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cb17bcf2e9e</guid>
            <category><![CDATA[architecture-components]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Leandro Martín Peralta]]></dc:creator>
            <pubDate>Fri, 24 Nov 2017 00:44:01 GMT</pubDate>
            <atom:updated>2017-11-24T01:48:02.871Z</atom:updated>
            <content:encoded><![CDATA[<p>I would like to share with you a way to create reactive <em>Activities and Fragments</em> using the <em>Architecture Components Library</em>, <em>RxJava </em>and <em>Kotlin</em>. I am not going to explain each of them in depth. However, even if you are not familiar with the aforementioned tools, I believe the code provided is simple enough for any <em>Android </em>developer to follow.</p><p>I would like to begin with BaseViewModel class to get some concepts out of the way from the start:</p><pre><strong>abstract class </strong>BaseViewModel&lt;State, Event&gt;(<br>        state: State,<br>        reducer: (State, Event) -&gt; State<br>) : ViewModel() {<br>    <strong>val liveState</strong>: LiveData&lt;State&gt;<br>    <strong>val events</strong>: Observer&lt;Event&gt;<br>    <strong>private val disposable</strong>: Disposable<br><br>    <strong>init </strong>{<br>        <strong>liveState </strong>= MutableLiveData&lt;State&gt;()<br>        <strong>events </strong>= PublishSubject.create()<br>        <strong>disposable </strong>= events.scan(state, reducer)<br>            .subscribe(<strong>{ liveState</strong>.<em>value </em>= <strong>it }</strong>)<br>    }<br><br>    <strong>override fun </strong>onCleared() {<br>        <strong>super</strong>.onCleared()<br>        <strong>events</strong>.onComplete()<br>        <strong>disposable</strong>.dispose()<br>    }<br>}</pre><p>ViewModel is a class from the <em>Architecture Components Library</em> for <em>Android</em>. It was created to solve a common issue with the platform: surviving configuration changes (e.g.: rotating the device). They are meant to be used to hold the <em>State </em>of our <em>View </em>(<em>Activity </em>or<em> Fragment</em>). The way we expose the <em>State</em> is by publishing it using <em>LiveData</em>: a sort of <em>Observable</em> that is aware of the life-cycle of our <em>View</em>.</p><p>The <em>State</em> is not static. It will change after certain <em>Events</em> occur. We can represent this fact as function: f(old_state, event) = new_state. This type of functions are commonly referred to as <em>Reducers</em>. What the scan operator does is to take the latest <em>State</em> and pass it through the <em>Reducer</em> to obtain a new <em>State</em> every time an <em>Event</em> occurs.</p><p>Do not worry too much if you do not fully understand the code above. What BaseViewModel allows us to do is focus on the three main concepts mentioned before: <em>State</em>, <em>Events </em>and <em>Reducer</em>. Next, we are going to define the <em>State</em> of a counter:</p><pre><strong>data class </strong>CounterState(<strong>val count</strong>: Int)</pre><p>For such a simple example, we just need to keep track of the current count so we can display on screen. Notice count is immutable, meaning you cannot assign a different value after State has been instantiated.</p><p>We are now going to define a few <em>Events </em>that can alter the <em>State</em> of our counter:</p><pre><strong>sealed class </strong>CounterEvent {<br>    <strong>object </strong>Increment : CounterEvent()<br>    <strong>data class </strong>Add(<strong>val quantity</strong>: Int) : CounterEvent()<br>}</pre><p>We defined only two of the possible events. Increment does not carry any parameters, so we declare it as an object. Add, on the other hand, carries a quantity to be added to the counter, so we declare it as a data class.</p><p>By using Kotlin’s sealed class we can define a finite number of well-known <em>Events </em>that can occur. This is important for when we write the <em>Reducer</em> function for our <em>ViewModel</em>:</p><pre><strong>class </strong>CounterViewModel : BaseViewModel&lt;CounterState, CounterEvent&gt;(<br>        CounterState(count = 0),<br>        <strong>{ </strong>state, event <strong>-&gt;<br>            when </strong>(event) {<br>                <strong>is </strong>CounterEvent.Increment -&gt; state.copy(<br>                        count = state.<strong>count </strong>+ 1<br>                )<br>                <strong>is </strong>CounterEvent.Add -&gt; state.copy(<br>                        count = state.<strong>count </strong>+ event.<strong>quantity<br>                </strong>)<br>            }<br>        <strong>}<br></strong>)</pre><p>For brevity, I declared the <em>Reducer</em> in the constructor. All we are doing is specifying the initial state, making sure count is 0 to begin with. When an increment occurs, we copy the previous <em>State</em> and add 1 to count . When an addition happens, we also copy the previous <em>State</em> and add the quantity determined by the <em>Event</em> into count. It is important to copy the previous <em>State </em>because sometimes an <em>Event</em> modifies only part of it and we want the rest to remain the same.</p><p>As an exercise you can try to add the Decrement and Substract events and let the <em>Reducer </em>update the <em>State </em>appropriately. It is now time to put our new <em>ViewModel</em> to use:</p><pre><strong>class </strong>CounterActivity : AppCompatActivity() {<br><br>    <strong>override fun </strong>onCreate(savedInstanceState: Bundle?) {<br>        <strong>super</strong>.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_counter)<br><br>        <strong>val </strong>counterView = findViewById&lt;TextView&gt;(R.id.counter)<br><br>        <strong>val </strong>viewModel = ViewModelProviders.of(<strong>this</strong>)<br>                .get(CounterViewModel::<strong>class</strong>.<em>java</em>)<br><br>        viewModel.<strong>liveState</strong>.observe(<strong>this</strong>, <em>Observer </em><strong>{<br>            it</strong>?.<em>let </em><strong>{ </strong>(count) <strong>-&gt;<br>                </strong>counterView.<em>text </em>= <strong>&quot;Count: $</strong>count<strong>&quot;<br>            }<br>        }</strong>)</pre><pre>        findViewById&lt;Button&gt;(R.id.increment).setOnClickListener(<strong>{<br>            </strong>viewModel.<strong>events</strong>.onNext(CounterEvent.Increment)<br>        <strong>}</strong>)<br>    }<br>}</pre><p>When we create our activity we subscribe to liveState and populate the <em>TextView </em>with the new count every time there is an update. As an example, I implemented a <em>Listener </em>for the increment <em>Button </em>so it submits a new CounterEvent.Increment when clicked.</p><h3>Conclusion</h3><p>The approach I described above is not new. The goal is to have a single flow of events and states, forming a cycle that makes it easier to predict how the view is going to behave. By using <em>ViewModel </em>and <em>LiveData</em> we abstract away the complexity of the <em>Activity </em>and <em>Fragment </em>life-cycles, which could potentially introduce issues when handling events and subscriptions.</p><p>There are many things which haven’t been covered and I will leave it to the reader to experiment with the approach. However, it is important to mention that <em>Events</em> are not only user actions. In this example, events is and <em>Observer</em>. Therefore, it can be subscribed to other <em>Observables</em>, regardless of if they are bound to click events or network requests, as long as they return (or are mapped to) an expected <em>Event </em>type.</p><p>I hope this work serves a starting point for those of you trying to make your Android applications more reactive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cb17bcf2e9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ViewModel and LiveData with Dagger Android]]></title>
            <link>https://argenkiwi.medium.com/viewmodel-and-livedata-with-dagger-android-bae06482903b?source=rss-b6f2ae7fced5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bae06482903b</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[architecture-components]]></category>
            <category><![CDATA[dagger-2]]></category>
            <dc:creator><![CDATA[Leandro Martín Peralta]]></dc:creator>
            <pubDate>Sun, 19 Nov 2017 06:30:55 GMT</pubDate>
            <atom:updated>2017-11-19T06:30:55.483Z</atom:updated>
            <content:encoded><![CDATA[<p>I was given the task to make a small <em>Android </em>application as part of an interview process. I used the opportunity to write some <em>Kotlin </em>and learn about the <em>Android Architecture Components</em>, which had just reached their first stable release. I had already used <em>Dagger </em>for <em>Android </em>in the past and I wanted to find out how they fit together. I will share my findings with you in this tutorial.</p><p>Let’s begin by creating a new application using <em>Android Studio</em>’s wizard, making sure we select Empty Activity as the template for the project.</p><p>Next, let’s create a custom <em>Application </em>class:</p><pre><strong>class MyApplication : Application()</strong></pre><p>And then add a reference to it in our AndroidManifest.xml:</p><pre>&lt;application <strong>android:name=&quot;.MyApplication&quot;</strong> ... /&gt;</pre><p>Now we need to add <em>Dagger </em>as a dependency in our app module’s build.config file:</p><pre>...<br><strong>apply plugin: &#39;kotlin-kapt&#39;<br></strong>...<br>dependencies {<br>    ...    <br><strong>    implementation &#39;com.google.dagger:dagger:2.13&#39;<br>    kapt &#39;com.google.dagger:dagger-compiler:2.13&#39;<br>    implementation &#39;com.google.dagger:dagger-android:2.13&#39;<br>    implementation &#39;com.google.dagger:dagger-android-support:2.13&#39;<br>    kapt &#39;com.google.dagger:dagger-android-processor:2.13&#39;</strong><br>}</pre><p>We can now create a <em>Component </em>for our <em>Application</em>:</p><pre>class MyApplication : Application() <strong>{<br>    override fun onCreate() {<br>        super.onCreate()<br>        DaggerMyApplication_Component<br>            .builder()<br>            .create(this)<br>            .inject(this)<br>    }</strong></pre><pre><strong>    @dagger.Component<br>    internal interface Component : AndroidInjector&lt;MyApplication&gt; {<br>        @dagger.Component.Builder<br>        abstract class Builder <br>            : AndroidInjector.Builder&lt;MyApplication&gt;()<br>    }</strong><br><strong>}</strong></pre><p>I decided to include the <em>Component </em>as an internal interface of MyApplication for convenience, but you may want to extract it into its own file. All we are doing here is declaring a <em>Component </em>that is able to inject our <em>Application </em>class. However, we still have not added any <em>Module </em>so there is nothing to inject it with.</p><p>It is time to add a <em>Module </em>to our application which will provide an <em>Injector </em>for our <em>Activity</em>:</p><pre>class MyApplication : Application()<strong>, HasActivityInjector</strong> {<br>    <strong>@Inject<br>    lateinit var dispatchingActivityInjector :  <br>        DispatchingAndroidInjector&lt;Activity&gt;</strong></pre><pre><strong>    override fun activityInjector() :<br>       AndroidInjector&lt;Activity&gt; = dispatchingActivityInjector</strong></pre><pre>    ...</pre><pre><strong>    @dagger.Module<br>    internal abstract class Module {<br>        @ContributesAndroidInjector<br>        abstract fun mainActivity(): MainActivity<br>    }</strong></pre><pre>    @dagger.Component<strong>(modules = arrayOf(Module::class))</strong><br>    internal interface Component : AndroidInjector&lt;MyApplication&gt; {<br>        ...<br>    }<br>}</pre><p>We have just added a module to our <em>Component, </em>which will provide an <em>Activity Injector, </em>and implemented the HasActivityInjector interface to let <em>Dagger k</em>now the <em>Application </em>exposes it. With all this in place, we can now inject MainActivity:</p><pre>class MainActivity : AppCompatActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        <strong>AndroidInjection.inject(this)</strong><br>        setContentView(R.layout.activity_main)<br>    }<br>}</pre><p>All we have done so far is create a <em>Component </em>for our <em>Application </em>and let <em>Dagger </em>generate a <em>Subcomponent </em>(which is the <em>Activity Injector</em>) for our <em>Activity</em>. We are ready to introduce the <em>Architecture Components </em>library. Let’s add the required dependencies:</p><pre>dependencies {<br>    ...<br><strong>    implementation &quot;android.arch.lifecycle:extensions:1.0.0&quot;<br></strong>}</pre><p>Next, we are going to create a <em>ViewModel </em>for our <em>Activity </em>and a <em>Module </em>to provide it:</p><pre>class MainActivity : AppCompatActivity() {<br>    <strong>@Inject</strong><br>    <strong>internal lateinit var viewModel : ViewModel</strong></pre><pre>    ...<br>    <strong>internal class ViewModel :<br>         android.arch.lifecycle.ViewModel()</strong></pre><pre><strong>    @dagger.Module<br>    internal object Module {<br>        @JvmStatic<br>        @Provides<br>        fun viewModel(<br>            activity: MainActivity<br>        ) = ViewModelProviders<br>            .of(activity)<br>            .get(ViewModel::class.java)<br>    }<br></strong>}</pre><p>All that is left is to bind the new <em>Module </em>to the <em>Activity Injector</em>. For that, we need to update the <em>Application Component</em>:</p><pre>class MyApplication : Application(), HasActivityInjector {<br>    <strong>...</strong><br>    @dagger.Module<br>    internal abstract class Module {<br>        @ContributesAndroidInjector(<strong>modules = arrayOf(<br>            MainActivity.Module::class<br>        )</strong>)<br>        abstract fun mainActivity(): MainActivity<br>    }<br><strong>    ...<br></strong>}</pre><p>Congratulations! Your <em>Activity</em> now has its own <em>ViewModel</em>. It doesn’t do much at the moment but it means we are ready to introduce <em>LiveData </em>into the mix:</p><pre>class MainActivity : AppCompatActivity() {<br>    ...<br>    internal class ViewModel(<br>            <strong>greeting: MutableLiveData&lt;String&gt;</strong><br>    ) : android.arch.lifecycle.ViewModel() <strong>{<br>        val greeting: LiveData&lt;String&gt; = greeting<br>        init {<br>            greeting.value = &quot;Hello world!&quot;<br>        }</strong></pre><pre><strong>        class Factory </strong><a href="http://twitter.com/Inject"><strong>@Inject</strong></a><strong> constructor(<br>                private val greeting: MutableLiveData&lt;String&gt;<br>        ) : ViewModelProvider.Factory {<br>            override fun &lt;T : android.arch.lifecycle.ViewModel?&gt;   <br>                create(modelClass: Class&lt;T&gt;) = <br>                    ViewModel(greeting) as T<br>        }<br>    }</strong></pre><pre>    @dagger.Module<br>    internal object Module {<br><strong>        @JvmStatic<br>        @Provides<br>        fun greeting() = MutableLiveData&lt;String&gt;()</strong></pre><pre><strong>        </strong>@JvmStatic<br>        @Provides<br>        fun viewModel(<br>            activity: MainActivity<br>        ) = ViewModelProviders<br>            .of(activity<strong>, factory</strong>)<br>            .get(ViewModel::class.java)<br>    }<br>}</pre><p>There are a few things to consider here. As an example, we assign an initial value to our <em>LiveData </em>object when the <em>ViewModel </em>is initialized. The <em>Activity Module </em>now provides <em>LiveData </em>of <em>String</em>. Also, in order to let the <em>Architecture Components </em>library inject the <em>LiveData </em>into the <em>ViewModel </em>through its constructor, we need to add a Factory class and pass it as a parameter to theViewModelProviders.of() method.</p><p>Finally, we are going to bind the <em>LiveData </em>from our <em>ViewModel </em>to the view in our <em>Activity</em>:</p><pre>class MainActivity : AppCompatActivity() {<br>    ...<br><strong>    private lateinit var greetingView: TextView</strong></pre><pre>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        AndroidInjection.inject(this)<br>        setContentView(R.layout.activity_main)<br>        <strong>greetingView = findViewById(R.id.greeting)<br>        viewModel.greeting.observe(this, Observer { greeting -&gt;<br>            greetingView.text = greeting<br>        })<br>    </strong>}<br>    ...<br>}</pre><p>We can now say we have a working <em>Hello World</em> app using <em>Dagger</em>, <em>ViewModel </em>and <em>LiveData</em>. But there is one more thing I want to mention. Every time we call AndroidInjeciton.inject() we are actually recreating the object graph for the Activity. This means every time we rotate the screen and the activity is created again, we get a new instance of the <em>LiveData </em>object which is injected into yet another new <em>Factory </em>object.</p><p>The fact is the <em>ViewModel </em>outlives the <em>Activity</em>. Therefore, the second time ViewModelProvide.of(activity, factory) is called, the whole <em>Factory </em>object is ignored. That is a lot of wasteful memory allocation we would like to avoid. I came up with the following solution:</p><pre>class MainActivity : AppCompatActivity() {<br>    ...<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        <strong>try {<br>            viewModel = ViewModelProviders<br>                .of(this)<br>                .get(ViewModel::class.java)<br>        } catch (e: Throwable) {</strong><br>            AndroidInjection.inject(this)<br><strong>        }<br></strong>        ...<strong><br>    </strong>}<br>    ...<br>}</pre><p>Basically, attempting to retrieve the <em>ViewModel </em>without providing a <em>Factory </em>will throw an error the first time, in which case we will execute the injection. After that, we will be able to retrieve the <em>ViewModel </em>without the need of a <em>Factory</em>. Of course this approach can only be taken if the <em>Activity </em>is kept as dumb as possible and no other objects need to be injected to it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bae06482903b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>