<?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 Dai on Medium]]></title>
        <description><![CDATA[Stories by Dai on Medium]]></description>
        <link>https://medium.com/@daio?source=rss-c18fc69ba21b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Iee7ORiJsLrtoH1IuklX2Q.png</url>
            <title>Stories by Dai on Medium</title>
            <link>https://medium.com/@daio?source=rss-c18fc69ba21b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 08:19:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daio/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[Jetpack Compose Interop Part 2: Using Compose in Traditional Android Views and Layouts with…]]></title>
            <link>https://proandroiddev.com/jetpack-compose-interop-part-2-using-compose-in-traditional-android-views-and-layouts-with-a3c50fc2eaa5?source=rss-c18fc69ba21b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3c50fc2eaa5</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[views]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Dai]]></dc:creator>
            <pubDate>Tue, 20 Oct 2020 22:22:59 GMT</pubDate>
            <atom:updated>2020-10-22T19:16:28.787Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLBUAyTdsgegjC8zUnAgZA.png" /></figure><h3>Jetpack Compose Interop Part 2: Using Compose in Traditional Android Views and Layouts with ComposeView</h3><p><a href="https://medium.com/@daio/jetpack-compose-interop-part-1-using-traditional-views-and-layouts-in-compose-with-androidview-b6f1b1c3eb1">In Part 1</a> I demonstrated how we can use AndroidView to render traditional Views inside our Compose UI. For this part, we are now going to make newly created Compose UI components work inside traditional Views and Layouts with another special class, ComposeView.</p><p><strong>Note</strong>: Just like in part 1, I am not going to deep dive into Jetpack Compose and I do assume you have some basic knowledge of how to use Compose. However, it should be fairly easy to follow along without knowing too much.</p><p>You are probably wondering why would anyone want to put Compose UI into older views. If you are using Compose, why not just use it everywhere 😅. However, just like Kotlin interop, having the ability to progressively adopt something new allows us to overcome the learning curve while remaining productive. We can keep our code consistent but start using Compose in projects sooner. So let’s look at how we can achieve this interop and provide some examples of why it may be useful.</p><h3>ComposeView</h3><p>Again, this is not a poorly formatted title, but another useful class that, this time, allows us to easily place Compose UI into traditional UI. ComposeView extends from View so it allows us to use it like any other View in Android with one major difference, we can add Compose UI components using a convenient setContent method.</p><p>Let&#39;s look at a quick example to demonstrate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d842d336537d1dc698d1e61843a11f33/href">https://medium.com/media/d842d336537d1dc698d1e61843a11f33/href</a></iframe><p>So here we are creating a new ComposeView and attaching it to a parent container, just like we might do with any View. We then use setContent to render Compose UI, and in this case, a simple Text composable. It’s as simple as that! We can even use the ComposeView in XML layouts too. So taking the same example, let&#39;s do that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed57e8962e0ef64c0fc82bd4e452f9c0/href">https://medium.com/media/ed57e8962e0ef64c0fc82bd4e452f9c0/href</a></iframe><p>Our activity_main.xml now contains a ComposeView nested inside a LinearLayout. We use this to do the same as we did before, but instead of adding the ComposeView manually we grab the reference and call setContent to add our Text.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ff0b02e824d17c003038f0670984173/href">https://medium.com/media/6ff0b02e824d17c003038f0670984173/href</a></iframe><p>And there you go, we have our Compose UI being treated like a traditional View. This is a little messy though. Mixing the two like this is not great and what if we want to do something a bit more custom.</p><h3>AbstractComposeView</h3><p>As you start to adopt Jetpack Compose one thing you might not want to do is start flip-flopping between older UI and Compose UI in the same file (like we did in the example above). Doing it like that will start to blur lines between which bits are Compose and which are not as things get more complex. To solve this you might want to create a bit of abstraction to keep things cleaner and in general, hide what&#39;s going on under the hood. So let&#39;s take the same Text example above but use AbstractComposeView to create our own custom View that will wrap the Compose UI components.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/766a18cf61ba653ddf2cc378a2a7e788/href">https://medium.com/media/766a18cf61ba653ddf2cc378a2a7e788/href</a></iframe><p>And just like before, we can then use this either directly in code or in our layout file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/358c66b4b058ec35c28187861a67c26b/href">https://medium.com/media/358c66b4b058ec35c28187861a67c26b/href</a></iframe><p>So now we have a custom MyComposeView component that under the hood is rendering Composable UI, which is pretty awesome!🤩 The benefit here is you will be able to write new UI in Compose and retrofit them to your older screens with a simple wrapper View allowing you to maintain consistency in your codebase, which is particularly useful when you can’t refactor all features and views at once.</p><h4>Taking it a bit further</h4><p>The problem with the example above is the Text has a hardcoded value. So let’s take the same example and provide the ability to set the text dynamically. I have not added an example to use attrs here but setting a value to the Statefrom an attribute value on initwill work in the same way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b56e703df7e408b61b3f69896bcca08/href">https://medium.com/media/1b56e703df7e408b61b3f69896bcca08/href</a></iframe><p>In the new example, the MyComposeView now exposes a title field that we can use to update the text value whenever we want. I am not going to go into the details here, but just to note, the mutableStateOf function creates aStateobject that when its value is used inside Compose, it will automatically update the UI if the value changes. That’s exactly what we have done in the above example with text = titleText.value. Unlike LiveData you don’t need to explicitly observe and set values. Compose handles this for you.</p><p>We can now use our title setter wherever we want to update the title.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/512e13244ca445b6259907ab87c7b357/href">https://medium.com/media/512e13244ca445b6259907ab87c7b357/href</a></iframe><p>And there you go, we can now set the text for our custom AbstractComposeView without exposing anything from Jetpack Compose into our older Views and Layouts.</p><p>But that’s a little boring really. Let’s create something a bit more interesting.</p><h4>Live TV Featured/Recent Channels</h4><p>As part of our Live TV experience within <a href="https://medium.com/u/8f1bf8c9c8db">Plex</a>, we display a horizontal list of recently watched/Featured TV channels. The architecture around how we deliver and display dynamic lists like this within the app is a lot more complex than the example below but let&#39;s see if we can implement a basic version of this feature that creates a horizontal scrolling list of TV channels written in Compose but displayed as traditional View just like we did in the previous example.</p><p>First off let&#39;s define a ChannelCard composable and a Channel data class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7be68c3bda63ca3639e08108c9a6edd2/href">https://medium.com/media/7be68c3bda63ca3639e08108c9a6edd2/href</a></iframe><p>Our ChannelCard is a simple Card with rounded edges containing a single CoilImage. CoilImage is not part of the standard Compose toolkit and for anyone who is not aware, Coil is an image loading library for Android. We are using this simply to display the channel logo of each channel in the list. If you want to use CoilImage composable to load images in your projects you can find out more <a href="https://github.com/chrisbanes/accompanist/tree/main/coil">here</a>.</p><p>The ChannelCardon its own is only going to display a single channel. So let&#39;s create a ChannelCardRow composable that will render them in a horizontal list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2846584f7469a1a3822175dbcf0ebe0f/href">https://medium.com/media/2846584f7469a1a3822175dbcf0ebe0f/href</a></iframe><p>From the above snippet, you can see our ChannelCardRow is a simple lazy horizontal list (row), that creates a ChannelCard for each channel.</p><p>Now that we have all our Compose components defined, let’s create our AbstractComposeView implementation that will allow us to display our horizontal list of channels as a traditional Android View.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e686dcb0ded64827b11412aefac26f4a/href">https://medium.com/media/e686dcb0ded64827b11412aefac26f4a/href</a></iframe><p>As you can see, just like before we are using mutableStateOf for our list of Channel data. Our Content method override then displays aChannelCardRow connected to the State so that whenever we set the current channels we render them onto the UI.</p><p>Now for the final bit, let’s use our ChannelCardRow implementation of AbstractComposeView in our Activity and load in some channels from our ViewModel.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b1fc6189834e293754c06e49c96b333/href">https://medium.com/media/0b1fc6189834e293754c06e49c96b333/href</a></iframe><p>All wired up and 🥁…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*DspIeP8A5zhl_ECplKVwag.gif" /><figcaption>ChannelCardRow Android View showing Channels</figcaption></figure><p>And there you go, we have a nice little reusable View that is using the just as reusable Compose UI components under the hood to display a horizontal list of TV Channels. And as you start to adopt more Compose in your app you can remove the traditional wrapper layers as and when they become obsolete.</p><h3>Summary</h3><p>The point of these blog posts was more to show what is possible for Compose interop. I can provide more details but hopefully, this and <a href="https://medium.com/@daio/jetpack-compose-interop-part-1-using-traditional-views-and-layouts-in-compose-with-androidview-b6f1b1c3eb1">Part 1 </a>provide enough detail to get you started and thinking about how you might adopt and interop Compose in your projects as things begin to stabilise. And just to recap:</p><ol><li>Use <strong>AndroidView</strong> to render traditional Views in your Compose UI (<a href="https://medium.com/@daio/jetpack-compose-interop-part-1-using-traditional-views-and-layouts-in-compose-with-androidview-b6f1b1c3eb1">Part 1</a>).</li><li>Use <strong>ComposeView</strong>/<strong>AbstractComposeView</strong> to render Compose UI in traditional Android Views and Layouts.</li></ol><p>I’m Dai, an Android Engineer for <a href="https://medium.com/u/8f1bf8c9c8db">Plex</a>. All views are my own.</p><p>Twitter: <a href="https://twitter.com/daioio">@daioio</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3c50fc2eaa5" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/jetpack-compose-interop-part-2-using-compose-in-traditional-android-views-and-layouts-with-a3c50fc2eaa5">Jetpack Compose Interop Part 2: Using Compose in Traditional Android Views and Layouts with…</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[Jetpack Compose Interop Part 1: Using Traditional Views and Layouts in Compose with AndroidView]]></title>
            <link>https://proandroiddev.com/jetpack-compose-interop-part-1-using-traditional-views-and-layouts-in-compose-with-androidview-b6f1b1c3eb1?source=rss-c18fc69ba21b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6f1b1c3eb1</guid>
            <category><![CDATA[views]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[compose]]></category>
            <dc:creator><![CDATA[Dai]]></dc:creator>
            <pubDate>Tue, 20 Oct 2020 22:19:38 GMT</pubDate>
            <atom:updated>2020-10-22T19:16:21.862Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLBUAyTdsgegjC8zUnAgZA.png" /></figure><p>Like most Android developers following the development of Jetpack Compose you are probably wondering if you will need to rewrite your views or your entire app from the ground up. Well, it turns out, you might not have to, in fact, just like the days when we were all beginning to adopt Kotlin, we can slowly adopt new views and even make our current UI work with Jetpack Compose. It may actually be even more useful to interop between the two while Jetpack Compose becomes the default and your team gets more comfortable building UI in this new world.</p><p>This is Part 1: focusing on using traditional Android Layouts and Views inside Compose UI. <a href="https://medium.com/@daio/jetpack-compose-interop-part-2-using-compose-in-traditional-android-views-and-layouts-with-a3c50fc2eaa5">Part 2 is here</a>, if you want to see how to use Compose UI inside traditional Android Views.</p><p><strong>Note</strong>: I am not going to deep dive into Jetpack Compose and I do assume you have some basic knowledge of how to use Compose. However, it should be fairly easy to follow along without knowing too much.</p><h3>AndroidView</h3><p>☝️That title isn’t poorly formatted, that&#39;s actually a very convenient class in the Jetpack Compose library that allows us to easily use traditional Views, ViewGroups, etc inside your @Composable UI components. So let&#39;s look at an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f9609c0a0666c9f01ba70f5dcc0b5d7/href">https://medium.com/media/1f9609c0a0666c9f01ba70f5dcc0b5d7/href</a></iframe><p>So from the above snippet, you can see we are using the `AndroidView` composable allowing us to render a TextView within our BasicList. The AndroidView takes a viewBlock lambda parameter where you can return any View.class. So already you can see how we can simply display a traditional TextView inside a Compose UI by creating it within our viewBlock. Conveniently we also get a Context within our block so we can easily use this to construct our views.</p><p>Now anyone who has played around with Jetpack Compose is probably thinking: <em>“Why would you want to use a TextView in Compose?”</em>. And they would be right to ask that since Compose already has a Text composable to render text.</p><p>So let&#39;s take a less contrived example where AndroidView is useful.</p><h3>Libraries and Dependencies</h3><p>You can probably guess from the heading where this is going. We all use libraries and SDKs within our apps and these libraries are hardly going to rewrite everything in Compose. At least not in the near future. Some common examples of this will be things like map SDKs or media players like ExoPlayer.</p><p>With this in mind, let&#39;s take the map example for a spin. I am going to use <em>Here</em> maps for this example but it will work just as well with Google Maps. I have also left out the tutorial on setting up <em>Here</em> maps as it&#39;s not really what this post is about, but you can easily explore the Lite SDK by following their documentation <a href="https://developer.here.com/documentation/android-sdk-lite/4.4.4.0/dev_guide/topics/quick-start.html">here</a></p><p>The Here Maps Lite SDK provides us with a MapViewLite traditional Android view component that we want to render in our Compose UI. So we are going to create our own MapView composable that will simply wrap the MapViewLite by using the same AndroidView class we used above with the TextView example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaf96a78677816484361db563aa8c9c7/href">https://medium.com/media/eaf96a78677816484361db563aa8c9c7/href</a></iframe><p>And then let&#39;s use our new MapView composable in a full-screen Activity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53cf224cf9d4bf3f67532673ed553bdc/href">https://medium.com/media/53cf224cf9d4bf3f67532673ed553bdc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*CkiiYCrY2JOMhCPXwQ91zA.gif" /><figcaption>MapView composable in full-screen Activity</figcaption></figure><p>And there you go, we have our Here map displaying within a Compose UI without having to write our own Map UI 😅.</p><p>This example is useful to see what we can do and that it is possible to use older Android views from dependencies that are not going to be rewritten anytime soon in Jetpack Compose, but it&#39;s still a bit simple so let&#39;s use a current more complex real-world UI.</p><h3>Plex App</h3><p>Over the past year, I have been working on a TV guide within the Plex app. It has taken a considerable amount of work and is something that is continually being refined and enhanced with new features.</p><h4>TVGuideView</h4><p>In the Plex app the TVGuideView is basically a composite View class that nicely wraps up the TV guide for support on TV and Mobile devices. So let&#39;s do the same thing we did before with maps (create a composable view) but this time with the TVGuideView</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38cd2c04701775d94474d732665945da/href">https://medium.com/media/38cd2c04701775d94474d732665945da/href</a></iframe><p>Now we have our new GuideView let&#39;s use that in our Activity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8cc71aad836d730a46cb34eef3c75c1/href">https://medium.com/media/e8cc71aad836d730a46cb34eef3c75c1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*ryEhuy83C3vU8mRYm-s3jg.gif" /><figcaption>TVGuideVIew used in Jetpack Compose</figcaption></figure><p>And there you go, our original TVGuideView can now be used within our Compose UI without having to be rewritten. And since we are now in Compose we can easily build and decorate the UI around it using Compose components. So let&#39;s add a ConstraintLayout (the Compose one) and a dumb heading to our Compose UI.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05da511929ad679de36b496469ed2476/href">https://medium.com/media/05da511929ad679de36b496469ed2476/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*7yWtUhICEndFp0_nSTOZQQ.gif" /><figcaption>TVGuideView with a dumb heading.</figcaption></figure><p>And that’s it, use AndroidView when you want to use traditional views in your Compose UI. <a href="https://medium.com/@daio/jetpack-compose-interop-part-2-using-compose-in-traditional-android-views-and-layouts-with-a3c50fc2eaa5">Check out Part 2</a> here where we use composable UI within traditional Android UI components.</p><h3>Summary</h3><p>The point of these blog posts was more to show what is possible for Compose interop. I can provide more details but hopefully, this and <a href="https://medium.com/@daio/jetpack-compose-interop-part-2-using-compose-in-traditional-android-views-and-layouts-with-a3c50fc2eaa5">Part 2 </a>provide enough detail to get you started and thinking about how you might adopt and interop Compose in your projects as things begin to stablise. And just to recap:</p><ol><li>Use <strong>AndroidView</strong> to render traditional Views in your Compose UI.</li><li>Use <strong>ComposeView</strong>/<strong>AbstractComposeView</strong> to render Compose UI in traditional Android Views and Layouts (<a href="https://medium.com/@daio/jetpack-compose-interop-part-2-using-compose-in-traditional-android-views-and-layouts-with-a3c50fc2eaa5">As outlined in Part 2</a>).</li></ol><p>I’m Dai, an Android Engineer for <a href="https://medium.com/u/8f1bf8c9c8db">Plex</a>. All views are my own.</p><p>Twitter: <a href="https://twitter.com/daioio">@daioio</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6f1b1c3eb1" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/jetpack-compose-interop-part-1-using-traditional-views-and-layouts-in-compose-with-androidview-b6f1b1c3eb1">Jetpack Compose Interop Part 1: Using Traditional Views and Layouts in Compose with AndroidView</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 detect Android application open and close: Background and Foreground events.]]></title>
            <link>https://medium.com/android-news/how-to-detect-android-application-open-and-close-background-and-foreground-events-1b4713784b57?source=rss-c18fc69ba21b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b4713784b57</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Dai]]></dc:creator>
            <pubDate>Sun, 17 Dec 2017 19:44:59 GMT</pubDate>
            <atom:updated>2017-12-21T15:00:00.966Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0yv2SdgJ60XdrlxmTGbaLA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/ZYBl6VnUd_0?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tim Mossholder</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This question seems to come up a lot. Especially if you are just starting out with Android development. It’s simply because there is nothing obvious built into the Android SDK enabling developers to hook into application lifecycle events. Activities and Fragments have all the callbacks under the sun to detect lifecycle change, but there is nothing for the whole application. So how do you detect when a user backgrounds and foregrounds your app. This is an example of how your could detect Application lifecycle events. Feel free to adjust and enhance it to suit your needs, but this idea should be enough to work for most applications with one caveat, it will only work for Android API level 14+(IceCreamSandwich 🍦🥪).</p><h3>Detecting App Lifecycle Evnts</h3><h4>Backgrounding</h4><p><a href="https://developer.android.com/reference/android/content/ComponentCallbacks2.html">ComponentCallbacks2 </a>— Looking at the documentation is not 100% clear on how you would use this. However, take a closer look and you will noticed the <strong>onTrimMemory</strong> method passes in a flag. These flags are typically to do with the memory availability but the one we care about is TRIM_MEMORY_UI_HIDDEN. By checking if the UI is hidden we can potentially make an assumption that the app is now in the background. Not exactly obvious but it should work.</p><h4>Foregrounding</h4><p><a href="https://developer.android.com/reference/android/app/Application.ActivityLifecycleCallbacks.html">ActivityLifecycleCallbacks </a>— We can use this to detect foreground by overriding <strong>onActivityResumed</strong> and keeping track of the current application state (Foreground/Background).</p><h3>Implementing a Foreground and Background Handler</h3><p>First, lets create our interface that will be implemented by a custom Application class. Something as simple as this:</p><pre>interface LifecycleDelegate {<br>    fun onAppBackgrounded()<br>    fun onAppForegrounded()<br>}</pre><p>Next, we need a class that is going to implement the <strong>ActivityLifecycleCallbacks</strong> and <strong>ComponentCallbacks2</strong> we discussed earlier. So lets create an <strong>AppLifecycleHandler</strong> and implement those interfaces and override the methods required. And lets take an instance of the <strong>LifecycleDelegate </strong>as a constructor parameter so we can call the functions we defined on the interface when we detect a foreground or background event.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42a23215ba34a94d3012ae5badcfb61b/href">https://medium.com/media/42a23215ba34a94d3012ae5badcfb61b/href</a></iframe><p>We outlined earlier that we could use <strong>onTrimMemory</strong> and the TRIM_MEMORY_UI_HIDDEN flag to detect background events. So lets do that now.</p><p>Add this into the <strong>onTrimMemory</strong> method callback body</p><pre>if (level == ComponentCallbacks2.<em>TRIM_MEMORY_UI_HIDDEN</em>) <strong>{<br>    </strong>// lifecycleDelegate instance was passed in on the constructor<br>    lifecycleDelegate.onAppBackgrounded()<br><strong>}</strong></pre><p>So now we have the background event covered lets handle the foreground event. To do this we are going to use the <strong>onActivityResumed</strong>. This method gets called every time any Activity in your app is resumed, so this could be called multiple times if you have multiple Activities. What we will do is use a flag to mark it as resumed so subsequent calls are ignored, and then reset the flag when the the app is backgrounded. Lets do that now.</p><pre>private var appInForeground = false<br><br>override fun onActivityResumed(p0: Activity?) {<br>   if (!appInForeground<em>) </em><strong>{<br>        </strong>appInForeground = true<br>        lifecycleDelegate.onAppForegrounded()<br>    <strong>}<br></strong>}</pre><p>So here we create a Boolean to flag the application is in the foreground. Now, when the application <strong>onActivityResumed</strong> method is called we check if it is currently in the foreground. If not, we set the <strong>appInForeground</strong> to true and call back to our lifecycle delegate (<strong>onAppForegrounded()</strong>). We just need to make one simple tweak to our <strong>onTrimMemory</strong> method to make sure that sets <strong>appInForeground</strong> to false.</p><pre>if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {<br>    appInForeground = false<br>    lifecycleDelegate.onAppBackgrounded()<br>}</pre><p>Now we are ready to use our <strong>AppLifecycleHandler</strong> class.</p><h4>AppLifecycleHandler</h4><p>Now all we need to do is have our custom Application class implement our <strong>LifecycleDelegate</strong> interface and register.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32a2492e8a57f419e76a1cf7e9ea912b/href">https://medium.com/media/32a2492e8a57f419e76a1cf7e9ea912b/href</a></iframe><p>And there you go. You now have a way of listening to your app going into the background and foreground.</p><p>This is only supposed to be used as an idea to adapt from. The core concept using <strong>onTrimMemory</strong> and <strong>onActivityResumed</strong> with some app state should be enough for most applications, but take the concept, expand it and break things out it to fit your requirements. For the sake of brevity I won’t go into how we might do multiple listeners in this post, but with a few tweaks you should easily be able to add a list of handlers or use some kind of observer pattern to dispatch lifecycle events to any number of observers. If anyone would like me to expand on this and provide a multi listener solution let me know in the comments and I can set something up in the example project on <a href="https://github.com/Daio-io/LifecycleDemoApp">GitHub</a>.</p><h3><strong>Update: Using Android Architecture Components</strong></h3><p>Thanks to <a href="https://medium.com/@yuriy.gladishev">Yurii Hladyshev</a> for the comment.</p><p>If you are using the Android Architecture Components library you can use the <a href="https://developer.android.com/reference/android/arch/lifecycle/ProcessLifecycleOwner.html"><strong>ProcessLifecycleOwner</strong></a> to set up a listener to the whole application process for onStart and onStop events. To do this, make your application class implement the <strong>LifecycleObserver </strong>interface and add some annotations for <strong>onStop</strong> and <strong>onStart</strong> to your foreground and background methods. Like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16df601977ace1c0cbea90e82d25a9a9/href">https://medium.com/media/16df601977ace1c0cbea90e82d25a9a9/href</a></iframe><p>Thanks for reading :).</p><p><a href="https://github.com/Daio-io/LifecycleDemoApp">Full code on GitHub</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b4713784b57" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/how-to-detect-android-application-open-and-close-background-and-foreground-events-1b4713784b57">How to detect Android application open and close: Background and Foreground events.</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Architecture Components: Handling clicks and single actions in your View Model with…]]></title>
            <link>https://medium.com/android-news/android-arch-handling-clicks-and-single-actions-in-your-view-model-with-livedata-ab93d54bc9dc?source=rss-c18fc69ba21b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab93d54bc9dc</guid>
            <category><![CDATA[android-architecture]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Dai]]></dc:creator>
            <pubDate>Thu, 30 Nov 2017 20:10:40 GMT</pubDate>
            <atom:updated>2017-12-12T09:06:59.005Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQpnWc-J4xwSedQ3LP0SQg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/CiUR8zISX60?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jakob Owens</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Android Architecture Components: Handling clicks and single actions in your View Model with LiveData.</h3><p>If you have started using the new Android Arch components you have probably reached a point and asked, “How do I handle a click or single event in my ViewModel?”. You have probably found this article because you have the same issue I had when trying to handle single events. This is just an idea so feel free to comment about other solutions and your thoughts 💭.</p><p><strong>A potential solution. Stateless LiveData.</strong></p><p>No one likes a null, so we are going to use it to our advantage here. The idea is simple. I will explain in code first:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3080cf2c01e130d6fcdfdedda942e42/href">https://medium.com/media/f3080cf2c01e130d6fcdfdedda942e42/href</a></iframe><p>So here we are extending the MutableLiveData class, creating our own ActionLiveData class. We then override the observe method, limiting the observers to only one by checking if the LiveData already hasObservers and using the super.observe call passing in a new Observer. The next bit is where we make this work. First we want to ignore null values and early return. If the LiveData value is not null we notify the observer and set the value back to null straight away. This means that the state of the LiveData is always null and the LiveData only ever emits new actions when the value is set again.</p><h3><strong>Example</strong></h3><p><strong>View Model</strong></p><p>So let’s create a simple ViewModel with the ActionLiveData<strong> </strong>(as described above) and use for a Snackbar message class .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3c8b298349169de46fb9a88deaef0b3/href">https://medium.com/media/c3c8b298349169de46fb9a88deaef0b3/href</a></iframe><p>In this file I have also included a SnackbarMessage data class which we use as our value type. <strong>ActionLiveData&lt;SnackbarMessage&gt;</strong>.</p><p><strong>Activity/Fragment</strong></p><p>In your Activity or Fragment, subscribe to the MainViewModel snackBarAction and show a new snack bar every time your receive an event. Set up a simple button and a method on the MainViewModel to be called every time it’s clicked, sending a new Snackbar message.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36b3d2bac2f06318b7d26c04a84479f5/href">https://medium.com/media/36b3d2bac2f06318b7d26c04a84479f5/href</a></iframe><p>I used a button here and snack bar in this example, but this action could be the result of anything. It could be a callback to say your data successfully saved to the server. Or that you want to launch a new Activity on click.</p><p><strong>Quick tip</strong>. If you use Kotlin why not make an extension function to clean up how you get view models. Something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df7ea9582b310b2e859bdd9a7f2d6de1/href">https://medium.com/media/df7ea9582b310b2e859bdd9a7f2d6de1/href</a></iframe><p><strong>Other Ideas</strong></p><p>This is just my idea on how to solve the problem. It’s simple and works for our use case. The hope is that something will eventually be added to the Arch components library to officially support single events in your view model. Search around the internet and you may find a solution on the Google Samples GitHub repository, <a href="https://github.com/googlesamples/android-architecture/blob/dev-todo-mvvm-live/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/SingleLiveEvent.java">SingleLiveEvent</a>. There are also some other solutions on the GitHub <a href="https://github.com/googlesamples/android-architecture-components/issues/63">issue here</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab93d54bc9dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/android-arch-handling-clicks-and-single-actions-in-your-view-model-with-livedata-ab93d54bc9dc">Android Architecture Components: Handling clicks and single actions in your View Model with…</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keep those background Services working when targeting Android Oreo (26)]]></title>
            <link>https://medium.com/android-news/keep-those-background-services-working-when-targeting-android-oreo-sdk-26-cbf6cc2bdb7f?source=rss-c18fc69ba21b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbf6cc2bdb7f</guid>
            <category><![CDATA[android-o]]></category>
            <category><![CDATA[android-oreo]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Dai]]></dc:creator>
            <pubDate>Wed, 23 Aug 2017 20:28:47 GMT</pubDate>
            <atom:updated>2017-09-03T20:19:08.722Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CqQTKb0N2o0suacfiluO8w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/2zLEAIZi92M?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Mike Wilson</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>So you just started targeting Android Oreo and you have forgotten about thoses Services you created to update your widgets in the background.</p><p>You may or may not be aware that when you start targeting Android Oreo there are execution <a href="https://developer.android.com/preview/features/background.html#services">limits for background Services</a>. In summary you can only start background Services from something that is considered to be in the foreground - foreground is defined in the link above. WidgetProviders are BroadcastReceivers for Widgets, therefore starting a Service from a WidgetProvider would be considered background.</p><p><strong>Just to note:</strong> These backgound execution limits do not affect Bound Services. If you declare a Bound Service, other components can bind to that service whether or not your app is in the foreground.</p><p>By now you have probably heard of the JobScheduler and you might be thinking you are going to have to refactor all your background Services to use this instead.</p><p>Well there is one very simple fix for you. JobIntentService.</p><h4>JobIntentService</h4><p>The JobIntentService works in the same way as a Service however it enqueues the work into the JobScheduler on compatible Android targets. This means you can easily convert your Services and IntentServices into a JobIntentService and keep the same functionality. The JobIntentService also exposes a static method to start the service (`JobIntentService.enqueueWork()`). You may be wondering how this will work on versions of Android that do not currently support the JobScheduler. Well, part of the beauty of the JobIntentService is that it will handle compatibaility for you. If the app is running on a device lower than Android Oreo it will call Context.startService otherwise it will use the JobScheduler.</p><h4>Converting to JobIntentService</h4><p>It’s so easy I can do this bit in snippets of Kotlin.</p><p>ExampleIntentService</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4fdfbaf0404eb3450588deb525fcedd/href">https://medium.com/media/b4fdfbaf0404eb3450588deb525fcedd/href</a></iframe><p>ExampleJobIntentService</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/423a5ea8c8f7f7989bdd52e6d272a502/href">https://medium.com/media/423a5ea8c8f7f7989bdd52e6d272a502/href</a></iframe><p>Done.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d5ed86969e145a4a769fdc4bb32f7b2/href">https://medium.com/media/9d5ed86969e145a4a769fdc4bb32f7b2/href</a></iframe><p>Just remember to register your service in the Manifest and add the BIND_JOB_SERVICE permission.</p><h4>Things to Note</h4><ul><li>When running on Android Oreo devices the JobIntentService uses the JobScheduler. This will handle the Wake Locks for you. On any device pre Android Oreo, the JobIntentService will set up Wake Locks through the PowerManager, so make sure you require the `WAKE_LOCK` permission in your manifest.</li></ul><p>` &lt;uses-permission android:name=”android.permission.WAKE_LOCK” /&gt;`</p><ul><li>When running on anything less than Android Oreo the service will start almost instantly. On Android Oreo it will be subject to JobScheduler policies, in other words it will not run while the device is dozing and may get delayed more than a usual service when the system is under heavy load.</li><li>On pre Android Oreo the service can run indefinitely but on Android Oreo it will adhere to the usual JobService execution type limits. At which point it will stop (not the process) and continue execution at a later time.</li></ul><p>You can find more about the JobIntentService <a href="https://developer.android.com/reference/android/support/v4/app/JobIntentService.html">here</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbf6cc2bdb7f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/keep-those-background-services-working-when-targeting-android-oreo-sdk-26-cbf6cc2bdb7f">Keep those background Services working when targeting Android Oreo (26)</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This simple trick will have you creating multiple returns in Kotlin.]]></title>
            <link>https://medium.com/android-news/this-simple-trick-will-have-you-creating-multiple-returns-in-kotlin-37b9fe2a2f9f?source=rss-c18fc69ba21b------2</link>
            <guid isPermaLink="false">https://medium.com/p/37b9fe2a2f9f</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Dai]]></dc:creator>
            <pubDate>Mon, 22 May 2017 15:08:57 GMT</pubDate>
            <atom:updated>2017-05-24T19:01:18.759Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kg1j_R_WnsNlbtfWlBhJyA.jpeg" /></figure><p>Some languages, such as Go, allow for multiple returns. In Go its commonly used to return an error or the expected result.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7994b86f5eca157ee377b2816911415/href">https://medium.com/media/c7994b86f5eca157ee377b2816911415/href</a></iframe><p>In Kotlin we don’t necessarily have multiple returns, but we can achieve the same result using destructuring.</p><h4>Destructuring</h4><p>Destructuing is a way of breaking down an object properties into individual variables. For example, lets say we have a normal data class with 3 properties</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43544724f9496e41b7c1e78107b5b3df/href">https://medium.com/media/43544724f9496e41b7c1e78107b5b3df/href</a></iframe><p>In the example above you can see we have created a simple Car data class and used parenthesis to pull out the properties and assign them to individual values. This is destructuring.</p><pre>val (make, _, model) = car1</pre><p>We can also ignore values we do not care about by using an underscore.</p><p>At this point you may have already figured out where we are going with this..</p><h4>The Main Event: Multiple Returns</h4><p>To achieve multiple returns in Kotlin all we need to do is destructure something like a Result data class. On this data class we can add two properties, lets say something like our Go example at the top of this post, result and error. For the purpose of this example I am going to just use String for the result and error types but you can use whatever you want really.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd285e7890a58fdd113fb1cfdab99471/href">https://medium.com/media/cd285e7890a58fdd113fb1cfdab99471/href</a></iframe><p>Working from the top, we define a data class with result and error as the two properties. I have made error optional and set its default to null, but you should do whatever makes more sense for your use case.</p><p>We then define a function that returns our Result data class after doing some task. This could be anything that could potentially fail and return an error or succeed and return the intended result.</p><p>The last line is where the multiple return finally takes shape. We use the Result returned from the function and desctructure the properties to give us both a result and err value returned from the same function.</p><p>There you go. Multiple Returns in Kotlin.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37b9fe2a2f9f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/this-simple-trick-will-have-you-creating-multiple-returns-in-kotlin-37b9fe2a2f9f">This simple trick will have you creating multiple returns in Kotlin.</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Super simple event bus with RxJava and Kotlin]]></title>
            <link>https://medium.com/android-news/super-simple-event-bus-with-rxjava-and-kotlin-f1f969b21003?source=rss-c18fc69ba21b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1f969b21003</guid>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[rxandroid]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Dai]]></dc:creator>
            <pubDate>Sat, 11 Mar 2017 00:05:45 GMT</pubDate>
            <atom:updated>2017-12-13T08:37:39.959Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PbAuKPfBbiid1QuK_QRBQA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/w8CcH9Md4vE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Herson Rodriguez</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I wanted to implement a simple event bus with RxJava and Kotlin that did not require any if statements, switch statements, when statements, reflection or any other nasty-ness when deciding which consumers should receive the events. I am assuming any readers have used RxJava before but the idea is simple.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f2776add7e512e20244d9146abd364c/href">https://medium.com/media/3f2776add7e512e20244d9146abd364c/href</a></iframe><p>All we do here is create a Kotlin object (RxBus), which will ensure the RxBus is a singleton. We then instantiate a private PublishSubject&lt;Any&gt; on the RxBus and expose a publish method on the RxBus to send onNext(Any) events into the publisher.</p><p>The bit that makes the bus flexible for new events going forward is the listen function. Firstly we only want the listen function to return the Observable interface to make sure an event consumer can only observe events.</p><p>Now, when we call the listen(Class&lt;T&gt;) function on a consumer, we pass in the Class type for the event data we want to receive when subscribing. We then create an Observable from the publisher that filters and only emits events of this type using the ofType() method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1bb6a5dbd8f5d78ddbced910c1a57f1/href">https://medium.com/media/a1bb6a5dbd8f5d78ddbced910c1a57f1/href</a></iframe><p>As you can see from the snippet above we can now listen out for any type of event just by using the class type. This also allows us to easily add or send new events without having to define separate event type classes or add any if/switch statements.</p><p>Omitted from this example, but I am assuming you have used RxJava and know to dispose of you subscriptions when finished.</p><p>That’s it. Thanks for reading.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=https%3A%2F%2Fupscri.be%2Fmedia%2Fform.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ae57c1b4448392f65f474b01a127fbf/href">https://medium.com/media/2ae57c1b4448392f65f474b01a127fbf/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1f969b21003" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/super-simple-event-bus-with-rxjava-and-kotlin-f1f969b21003">Super simple event bus with RxJava and Kotlin</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A few ways to implement a Swift like guard in Kotlin]]></title>
            <link>https://medium.com/android-news/a-few-ways-to-implement-a-swift-like-guard-in-kotlin-ffd94027864e?source=rss-c18fc69ba21b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffd94027864e</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Dai]]></dc:creator>
            <pubDate>Sun, 19 Feb 2017 18:35:13 GMT</pubDate>
            <atom:updated>2017-03-13T14:11:44.743Z</atom:updated>
            <content:encoded><![CDATA[<p>Before I started working with Kotlin, like most Android developers I developed applications in Java and in-between I learned Swift for iOS. One of the things I liked about Swift was the guard let syntax. Just seeing the guard keyword at the top of the method body was an instant indication that this function is going to return early or handle some potential errorneous parameter. So I started playing around with the ways you can achieve this in Kotlin. This guide is just to provide some ideas about how to achieve guard statements in Kotlin. Some people may not 100% agree with the ideas or may have some better solutions so feel free to post in the comments :).</p><p><strong>If you want the TL;DR version with just the code examples, skip to the bottom.</strong></p><h3>Optionals are different in Kotlin</h3><p>The way optionals work in Kotlin is very different to how they work in Swift. In Swift an optional is a special type, an Enum in fact. This Enum contains 2 cases, a Some(T) and a None, where T is the type being unwrapped from the Optional. When unwrapping the Optional, if there is a Some(T), the value will be returned. If there is a None, nil will be returned during an if let or guard let.</p><p>In Kotlin the compiler distinguishes between references that can be null and ones that can not be null by its ? in the type declaration. The compiler will then generate byte code that handles potential null references for you (provided you dont force (!!) access optional values). This makes the Kotlin compiler a little smarter since Optionals are not really “unwrapped”.</p><p>Thats a very simplified explanation so have a read around if you are curious to learn more about how Optionals work in both languages.</p><h3>If</h3><p>The first type of guard let we can do is a good old fashion if.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e8b0aa2cd44bae062d87ba0cf3d5f0e/href">https://medium.com/media/0e8b0aa2cd44bae062d87ba0cf3d5f0e/href</a></iframe><p>Thats it.</p><p>Since we have done a check for thing being null at the top of the function. The compiler is smart enough to know that anything accessing this property from that point on can safely assume it is not null. Meaning you no longer need to use the <strong>?</strong> or <strong>!!</strong> to access any properties on the optional value. You can also use the <strong>is</strong> keyword to null check and smart cast.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88dc4de255a781183c16721e7cecf8fd/href">https://medium.com/media/88dc4de255a781183c16721e7cecf8fd/href</a></iframe><p>However, both of these examples do not work for mutable (var) optional properties on class’s or in a situtaion where the var is not local to the null check. Since they could change, it prevents the compiler’s ability to smart cast.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea5baf22c270ed42b40eee034be33ca8/href">https://medium.com/media/ea5baf22c270ed42b40eee034be33ca8/href</a></iframe><p>So we need another solution. Kotlin contains so many nice features that writing if statements is a thing of the past. Im so used to not using them now I feel like im writing a hack when I do. So lets get rid of that if statement.</p><h4>takeIf (Kotlin 1.1).</h4><p>If you’re hipster enough and already using Kotlin 1.1 you may have noticed the <strong>takeIf</strong> general purpose extension function. <strong>takeIf</strong> does pretty much does what it says. It takes the value of the object it is being called on only if the given predicate is true.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4beb6640b7bbb3455be1d0e8fc049b9c/href">https://medium.com/media/4beb6640b7bbb3455be1d0e8fc049b9c/href</a></iframe><p>So, in the example we are basically saying assign the <strong>val something</strong> to <strong>thing</strong>, only if it is not null (checked with the ?) and is less than 10. Otherwise return early.</p><p>Its awesome but not everyone is hipster enough to be on 1.1 yet, so lets continue.</p><h4>let</h4><p>Kotlin contains several general extension functions that work great as a guard. The first one we will look at is <strong>let</strong>. By using the ? and the let function we can execute code only if the optional value is not null and return the last statement from within the let block parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e473794077b2e56d7b1ac12805920ca3/href">https://medium.com/media/e473794077b2e56d7b1ac12805920ca3/href</a></iframe><p>We now create a val <strong>something</strong> with the String “hello” only if <strong>thing</strong> is not null, but if <strong>thing</strong> is null then the <strong>something </strong>value will also be null. And thats not what we want.</p><p>We could use the <strong>it </strong>as the last statement in the let block which would return the value of thing if it is not null, like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae0eca92f42dc5114856d195baf1de63/href">https://medium.com/media/ae0eca92f42dc5114856d195baf1de63/href</a></iframe><p>But lets do something else.</p><h4>Elvis operator (?:)</h4><p>Enter Elvis. Lets do that same bit of code but use the elvis operator. Which looks like this: <strong>?.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9c68fed2b216cb1144bd58fc8801b82/href">https://medium.com/media/a9c68fed2b216cb1144bd58fc8801b82/href</a></iframe><p>The elvis operator is basically a more concise ternary. It works by executing the the first statement, if this is null it will execute the second statement. Its used mainly to return the statment value (like a ternary), but in the example above we are using it like a guard to return early. We can also use this in a even simapler case assign an Optional value to a new value or return early like so</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78166816346600bb66fc1f620f9ab502/href">https://medium.com/media/78166816346600bb66fc1f620f9ab502/href</a></iframe><h4>apply</h4><p>The let function returns the last statement, which is no use when we want to use the value of the optional we are checking. As I said, we could use the <strong>it </strong>keyword in the let block parameter but apply makes more sense here.</p><p>apply can be used in the same wayas let. The difference being apply always returns the value of its self i.e. this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5142895d0da29cb329999a7e6f421fa/href">https://medium.com/media/e5142895d0da29cb329999a7e6f421fa/href</a></iframe><p>No matter what the last statement is within the apply block, It will always return the value of the <strong>thing</strong> variable and by using the elvis operator again we just return if apply returns null.</p><h4>Extensions</h4><p>If you really, really want to have a guard keyword then the next best thing is creating an extension function. This is exactly what let and apply are. Extension functions added to any type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8eba1b53dc850269fcae97c3b762482b/href">https://medium.com/media/8eba1b53dc850269fcae97c3b762482b/href</a></iframe><p>In the above example we have defined a guard general purpose extension function to <strong>T </strong>(<strong>T.guard</strong>). This basically means we are adding the <strong>guard </strong>extension function to any type. The <strong>guard</strong> takes a single lambda which is only called if the the object calling <strong>guard</strong> is null. We then use this lambda block to return early.</p><h4>TL;DR</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e8b0aa2cd44bae062d87ba0cf3d5f0e/href">https://medium.com/media/0e8b0aa2cd44bae062d87ba0cf3d5f0e/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88dc4de255a781183c16721e7cecf8fd/href">https://medium.com/media/88dc4de255a781183c16721e7cecf8fd/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4beb6640b7bbb3455be1d0e8fc049b9c/href">https://medium.com/media/4beb6640b7bbb3455be1d0e8fc049b9c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9c68fed2b216cb1144bd58fc8801b82/href">https://medium.com/media/a9c68fed2b216cb1144bd58fc8801b82/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78166816346600bb66fc1f620f9ab502/href">https://medium.com/media/78166816346600bb66fc1f620f9ab502/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5142895d0da29cb329999a7e6f421fa/href">https://medium.com/media/e5142895d0da29cb329999a7e6f421fa/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8eba1b53dc850269fcae97c3b762482b/href">https://medium.com/media/8eba1b53dc850269fcae97c3b762482b/href</a></iframe><p>Thanks for reading. Feel free to leave some suggestions in the comments.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=https%3A%2F%2Fupscri.be%2Fmedia%2Fform.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ae57c1b4448392f65f474b01a127fbf/href">https://medium.com/media/2ae57c1b4448392f65f474b01a127fbf/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffd94027864e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/a-few-ways-to-implement-a-swift-like-guard-in-kotlin-ffd94027864e">A few ways to implement a Swift like guard in Kotlin</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>