<?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 Hamed Momeni on Medium]]></title>
        <description><![CDATA[Stories by Hamed Momeni on Medium]]></description>
        <link>https://medium.com/@2hamed?source=rss-14eb1fe936bb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*U0JzTy2AJp8ctRUnYPkcdw.jpeg</url>
            <title>Stories by Hamed Momeni on Medium</title>
            <link>https://medium.com/@2hamed?source=rss-14eb1fe936bb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 22:32:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@2hamed/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[Dependency Isolation in Go]]></title>
            <link>https://medium.com/@2hamed/dependency-isolation-in-go-afab00b5e4c9?source=rss-14eb1fe936bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/afab00b5e4c9</guid>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dependency-inversion]]></category>
            <dc:creator><![CDATA[Hamed Momeni]]></dc:creator>
            <pubDate>Tue, 22 Oct 2019 07:51:58 GMT</pubDate>
            <atom:updated>2019-10-23T06:35:08.546Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve never written any Go code, grasping the mechanics of its interfaces could be burdensome at first. The fact that you don’t need to explicitly declare that a struct implements a certain interface will make newcomers a little more than confused. But let me tell you this; it’s a tremendously powerful feature.</p><p>But first a little bit of history…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nky1uZpFvkELX3RRC8tQSw.jpeg" /><figcaption>Here is a little goofy gopher for you :)</figcaption></figure><p>If you’re a serious programmer you must be familiar with SOLID principles. The 5 principle which Uncle Bob coined and published as a guide for us to write good software. The fifth of those guidelines is the Dependency Inversion Principle which states:</p><blockquote>High-level modules should not depend on low-level modules. Both should depend on abstractions (e.g. interfaces).</blockquote><blockquote>Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.</blockquote><p>But that’s for Object Oriented Programming right?! Is Go even an object oriented language? No it’s not. And you should never think of it as one.</p><p>But even though Go is not an OO language, many of our previous practices holds true here too. Specially the Dependency Inversion Principle . So what’s Go’s interfaces have to do anything with it?</p><p>Let’s continue with an example. Imagine that you’re building a package which needs to store some data, but it doesn’t not care about where or how this data is stored. Let’s call it foo. Let’s also have Fooler interface which will have a Save func that another package will use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*XYFl7IVxpH0oMfskJ2lUUg.png" /></figure><p>As you can see the foo struct conforms to the Fooler interface. But where do we store the data? Let’s add an Storage interface so that we can use it to store some data.</p><p>But wait…!</p><p>We have no idea what functions that Storage interface is going to have. What if it names its Save function something like Store? What if it accepts different kinds of parameters in different order?</p><p>The cool thing here is, that we don’t really care about how or what methods that external persistence service will have. We define our own Storage interface and as long as it -the external service- conforms to our standards we can use it. Without any imports for external interfaces. As a matter of fact that other package doesn’t need to import anything from us too. That is called Duck Typing [1]. If it walks like duck and it quacks like a duck, then it is a duck.</p><p>So let’s define our interface like this.</p><figure><img alt="Storage interface in Go with Store and Fetch functions" src="https://cdn-images-1.medium.com/max/599/1*YKPSm5mLeKMmGQRV2XmWfw.png" /></figure><p>Now that we have our Storage we can refactor our foo struct.</p><figure><img alt="foo struct in Go that implements a Save function" src="https://cdn-images-1.medium.com/max/487/1*3bpDI0HlpErQln-TPQf18g.png" /></figure><p>We’re not done yet. We need a way to pass in the Storage instance to the foo package. It is conventional in Go to have an exported function which instantiates things for other packages to use. This is how it goes…</p><figure><img alt="A function to create a concrete implementation of the Fooler interafce" src="https://cdn-images-1.medium.com/max/675/1*7m9k6X3Q8x0PepUHbSR5pg.png" /></figure><p>So now let’s create a sample storage package to see how it goes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*i5HVJEiqlT_jQTj3BKD-zQ.png" /><figcaption>I purposefully named this package `datastore` to avoid confusing the less experienced</figcaption></figure><p>As you can see there is no import anywhere in both our packages. The only entity which needs to be aware of our individual interfaces is the higher level package which will pass the Datastore to the NewFooler function. Here is the main package that will glue these two packages together.</p><figure><img alt="Go’s main function" src="https://cdn-images-1.medium.com/max/447/1*XJrW8y6JcR7B_TNFgcs6ew.png" /><figcaption>Notice that `NewFooler` doesn’t complain about the type of datastore</figcaption></figure><p>main is the only package which needs to be aware of those 2 components. You now may begin to understand how powerful and flexible this feature is in creating highly <strong>decoupled</strong> software components.</p><p>Go is a simple enough language to learn but it is difficult master. It has many intricate features such as this one that only practice can make a perfect gopher.</p><p>Footnotes:</p><p>[1] Technically in Go Duck Typing is called Structural Typing since it is done at compile time whilst Duck Typing is done at run time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afab00b5e4c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code Coverage in Go]]></title>
            <link>https://medium.com/@2hamed/code-coverage-in-go-714374369b7b?source=rss-14eb1fe936bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/714374369b7b</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[code-coverage]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Hamed Momeni]]></dc:creator>
            <pubDate>Tue, 16 Jul 2019 07:54:19 GMT</pubDate>
            <atom:updated>2019-07-16T07:54:19.937Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re not writing tests for your code you should start right away. Writing tests not only makes sure that your codes are working the way they should, it is also a great way of thinking objectively about your class and functions. It may also lead you to write better code as a result.</p><p>But I’m not going to teach you how to write testable code as there are tons of high quality material on that out there. What we’re going to talk about here is Code Coverage and what it implies and how to use it in Go.</p><h3>Definition;</h3><p>Code Coverage shows how much of your code base is taking part in your tests. In other words it shows that with how much confidence you can say that your code is tested.</p><p>A low coverage is certainly an indication that not enough tests have been written to test every aspect of your code. A high coverage can indicate that your tests have been exhaustive enough to test most of your code base.</p><h3>Usage;</h3><p>Finding out the Code Coverage is certainly not something that can be done manually and there are tools for that. In Go as with many other tasks there is an excellent tool in the Go’s toolchain.</p><p>What we’re going to use here are the go test and the go tool cover commands. As a sample I’m going to use this open source project of mine to run these tools.</p><p><a href="https://github.com/2hamed/goronos">2hamed/goronos</a></p><p>The project uses Go Modules so in order to use it you should have at least Go v1.12 installed on your machine.</p><p>First and foremost run the go mod tidy to install the dependencies. As you can see most of the code is located under the scheduler package and we are going to run our tests on that package. To run the tests execute the following command in the project’s root folder:</p><pre>go test ./scheduler</pre><figure><img alt="go test ./scheduler result" src="https://cdn-images-1.medium.com/max/411/1*iTXwwlMZ-CLRX_CI1hQviQ.png" /></figure><p>As you can see it prints the result of our tests on stdout (and one test is failing but it doesn’t matter right now). So what about the coverage?</p><p>To get the code coverage we need to add another part to our test command and it is as follows:</p><pre>go test --coverprofile ./scheduler/.coverage ./scheduler</pre><p>By specifying the --coverprofile ./scheduler/.coverage parameter we tell the test tool to write the code coverage result in the file ./scheduler/.coverage . Let’s take a look at what is produces.</p><pre>mode: set<br>github.com/2hamed/goronos/scheduler/utils.go:17.51,19.21 1 1<br>github.com/2hamed/goronos/scheduler/utils.go:23.2,23.29 1 1<br>github.com/2hamed/goronos/scheduler/utils.go:28.2,28.14 1 1<br>github.com/2hamed/goronos/scheduler/utils.go:19.21,21.3 1 1<br>github.com/2hamed/goronos/scheduler/utils.go:23.29,24.13 1 1<br>github.com/2hamed/goronos/scheduler/utils.go:24.13,26.4 1 1<br>github.com/2hamed/goronos/scheduler/utils.go:32.73,34.21 1 1<br>github.com/2hamed/goronos/scheduler/utils.go:38.2,38.29 1 1<br>github.com/2hamed/goronos/scheduler/utils.go:43.2,43.14 1 1<br>github.com/2hamed/goronos/scheduler/utils.go:34.21,36.3 1 1<br>github.com/2hamed/goronos/scheduler/utils.go:38.29,39.13 1 1<br>github.com/2hamed/goronos/scheduler/utils.go:39.13,41.4 1 1<br>github.com/2hamed/goronos/scheduler/utils.go:47.76,48.21 1 1<br>...</pre><p>Well I can tell you that is not helpful at all. And here comes the other tool that we spoke of. Let’s run the following command next:</p><pre>go tool cover -html ./scheduler/.coverage</pre><p>Running that command should open your browser with something like the following image inside it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0cYblsveX5ofF3SZcLzNLQ.png" /></figure><p>This certainly is useful as it displays your files distinctively with all their code and where they stand in your tests. Whether they are covered or not. You can even save this file as an HTML by supplying the -o param with the output file address.</p><p>Using this tool you can detect the paths that are not covered by your tests and you should write additional tests to cover them as well.</p><h3>Conclusion;</h3><p>Writing good tests takes practice and what is required to write good tests is writing good (testable) code. By using code coverage you can make sure that you’re considering every aspect of your code and it all leads to a better software.</p><p>Be sure to leave a clap on this post if you find it useful. You’re also welcome to visit my <a href="https://github.com/2hamed">Github profile</a> and checkout the projects I’m currently working on and you’re more than welcome to make pull requests on them.</p><p>Cheers. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=714374369b7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I approached Android Navigation Component]]></title>
            <link>https://medium.com/@2hamed/how-i-approached-android-navigation-component-7fbb8cf6f83a?source=rss-14eb1fe936bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fbb8cf6f83a</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[navigation]]></category>
            <dc:creator><![CDATA[Hamed Momeni]]></dc:creator>
            <pubDate>Sun, 23 Dec 2018 15:22:15 GMT</pubDate>
            <atom:updated>2018-12-23T15:22:15.899Z</atom:updated>
            <content:encoded><![CDATA[<p>Reader’s Alert: This isn’t a complete tutorial on how to implement Android Navigation Component. It’s more of a personal reflection on how to approach it. So if you’re a complete stranger to Android Navigation Component I suggest you start with another, better tutorial.</p><p>Building Single Page Applications has always been a demanding task in Android. Having to deal with Fragments and all of their lifecycle and intricacies is not for the faint of heart.</p><p>One of those special operations that requires hours of head-smashing against walls is having to deal with Fragment Transactions. Trust me it’s always been a pain in the back to get things right (transition between different Fragments and animations and stuff).</p><p>So finally Google decided to relieve us of the pain. Little did we know that we’re in for a not so much fun ride again.</p><p>I’m talking about the Android Navigation Component which is now part of Android Jetpack. Don’t get me wrong. I’m not saying that it’s as nasty as having to deal with Fragment Transactions themselves, but it’s not so much easy as using a little bit of coding and suddenly all our worries disappear.</p><p>So enough of talking. I’m going walk you through how I approached Android Navigation and how I used it to build a SPA.</p><p>Here are the tools I’ll be using to achieve our purpose:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e16bb2d6bcca4f42d2d91e783e326dc6/href">https://medium.com/media/e16bb2d6bcca4f42d2d91e783e326dc6/href</a></iframe><p>We will be using RxJava’s PublishProcessors as the event bus for transferring different navigation events across the application’s components. You can use GreenRobot’s <a href="https://github.com/greenrobot/EventBus">EventBus</a> or Android’s built-in Broadcasts for this purpose as well. It really doesn’t matter as long as you can deliver events to your navigation controller.</p><p>We will also be using Dagger2 to handle our PublishProcessor creation and injection.</p><p>I assume you’re using these tools already in your applications these days. Right?!</p><p>Since this is not an article on how to add Android Navigation Component to an Android application I’ll skip parts about adding the nav component to the project and jump right to the subject of delivering navigation events from different parts to the NavController object. You can check <a href="https://developer.android.com/topic/libraries/architecture/navigation/navigation-implementing">Google’s guide on Implementing navigation with Navigation Architecture Component</a> to get up to speed.</p><p>Before anything else we need a PublishProcessor to act as our communications bridge and I’m going to put it inside a Dagger module so that it can be injected anywhere it’s needed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49fae6a7724c279e16dc88e21f4f30cd/href">https://medium.com/media/49fae6a7724c279e16dc88e21f4f30cd/href</a></iframe><p>And a NavEvent class to act as the base class for different navigation events. We’re going add a destination property to specify where this navigation event is leading. As you can see I’ve used an enum for this purpose.</p><pre>class NavEvent(<br>    val destination: Destination<br>) {<br>    enum class Destination {<br>        ONE, TWO, THREE, FOUR<br>    }<br>}</pre><p>And to start receiving navigation events we should subscribe to our PublishProcessor in the MainActivity class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6c61d714d85b8d28e7727a320906fac/href">https://medium.com/media/d6c61d714d85b8d28e7727a320906fac/href</a></iframe><p>For the sake of this article I’m going to have 4 separate fragment as our navigation destinations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*R-Cve_S4_lhDz1vPJkIsGQ.png" /></figure><p>So the actual navigation will happen inside the subscribe method of our Publisher object:</p><pre>navEvents.subscribe <strong>{<br>    </strong>when (<strong>it</strong>.destination) {<br>        NavEvent.Destination.ONE -&gt; <em>TODO</em>()<br>        NavEvent.Destination.TWO -&gt; <em>TODO</em>()<br>        NavEvent.Destination.THREE -&gt; <em>TODO</em>()<br>        NavEvent.Destination.FOUR -&gt; <em>TODO</em>()<br>    }<br><strong>}</strong></pre><p>After adding the navigation bit our subscribe method will be like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba4c331cb97ce245844c8f4011905302/href">https://medium.com/media/ba4c331cb97ce245844c8f4011905302/href</a></iframe><p>Now you just need to send your NavEvents using the publisher from inside the Fragments. This is a sample for one of the Fragments:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cdbed1cb097295b389ad70e771851f1/href">https://medium.com/media/2cdbed1cb097295b389ad70e771851f1/href</a></iframe><p>You can create the rest following the same pattern.</p><p>Now if you have implemented all the fragments, go ahead and run the app inside an emulator or a physical device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bns1RUXhK4gKGWMCwLl2Sw.gif" /></figure><p>Wait! What happened?! Why did the app crash upon clicking on GO TO 3 ?!!</p><p>Well here is the logcat error of what happened:</p><pre>Caused by: java.lang.IllegalArgumentException: navigation destination com.hmomeni.androidnavigationsample:id/action_fragmentOne_to_fragmentThree is unknown to this NavController</pre><p>Well this happens because our NavController is currently on FragmentTwo and when we send it the NavEvent.Destination.THREE it wants to execute:</p><pre>navController.navigate(R.id.<em>action_fragmentOne_to_fragmentThree</em>)</pre><p>What? fragmentOne to fragmentThree? But we’re on FragmentTwo!</p><p>And that makes the app crash.</p><p>And workaround it we need to explicitly check the current destination on the navController and use the correct action accordingly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a37f1a97857cac9037ff78214317f262/href">https://medium.com/media/a37f1a97857cac9037ff78214317f262/href</a></iframe><p>Now everything should be in order and no crash should occur if you run the app.</p><p>This is a bit tedious if you ask me but I haven’t come up with a way to avoid having to manage all these destination checks. You can imagine it becomes a chore for a big application.</p><p>As always all the code in this article is available at the following Github repository.</p><p><a href="https://github.com/2hamed/android-nav-sample">2hamed/android-nav-sample</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fbb8cf6f83a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Filterable RecyclerView in Android — The How To]]></title>
            <link>https://medium.com/android-news/filterable-recyclerview-in-android-the-how-to-a9ade9cd26?source=rss-14eb1fe936bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9ade9cd26</guid>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Hamed Momeni]]></dc:creator>
            <pubDate>Tue, 14 Aug 2018 19:17:04 GMT</pubDate>
            <atom:updated>2018-08-27T06:13:26.987Z</atom:updated>
            <content:encoded><![CDATA[<p>It happens quite often that we need a list of items in our Android application. And sometimes this list needs to have filtering capabilities for the users so they can find the relevant results in potentially a long list. In this post I am going to demonstrate how to achieve that purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*aQ4UrmKECjKHQAovlc1XFA.png" /><figcaption>Move along, this is just for Medium’s sake</figcaption></figure><p>So first things first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*qcbWXOf3NXavnYYxYD2TYQ.gif" /><figcaption>A look of what we’re trying to achieve</figcaption></figure><p>The ingredients…</p><p>We are going to use <a href="https://github.com/ReactiveX/RxJava">RxJava</a> and <a href="https://github.com/JakeWharton/RxBinding">RxBinding</a> libraries for this example (I assume you are using them in your projects these days) and to sweeten things up we’ll be using the <a href="https://developer.android.com/topic/libraries/architecture/viewmodel">ViewModel</a> package which is now a part of the Android JetPack toolbox.</p><p>The dependencies go as follows:</p><pre>implementation &#39;io.reactivex.rxjava2:rxandroid:2.0.1&#39;<br>implementation &quot;io.reactivex.rxjava2:rxjava:2.1.9&quot;<br>implementation &quot;io.reactivex.rxjava2:rxkotlin:2.2.0&quot;<br>implementation &#39;com.jakewharton.rxbinding2:rxbinding-kotlin:2.1.1&#39;</pre><pre>implementation &quot;android.arch.lifecycle:extensions:1.1.1&quot;</pre><p>Be sure to always use the latest versions of each library.</p><p>For the sake of this example I’ll be using the Post object to populate my RecyclerView with.</p><pre>data class Post(<br>        val id: Int,<br>        val title: String,<br>        val content: String<br>)</pre><p>And a simple RecyclerView adapter.</p><pre>class SimpleRecyclerAdapter(private val context: Context, private val posts: List&lt;Post&gt;) : RecyclerView.Adapter&lt;SimpleRecyclerAdapter.PostHolder&gt;() {<br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostHolder {<br>        return PostHolder(LayoutInflater.from(context).inflate(R.layout.<em>rcl_item_post</em>, parent, false))<br>    }<br><br>    override fun getItemCount() = posts.size<br><br>    override fun onBindViewHolder(holder: PostHolder, position: Int) {<br>        holder.bind(posts[position])<br>    }<br><br>    class PostHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {<br>        fun bind(post: Post) {<br>            itemView.titleView.<em>text </em>= post.title<br>            itemView.contentView.<em>text </em>= post.content<br>        }<br>    }<br>}</pre><p>Now we need a ViewModel for our MainActivity. Let’s name it MainViewModel .</p><pre>class MainViewModel : ViewModel() {<br><br>    private val originalPosts = <em>listOf</em>(<br>            Post(1, &quot;Ubi est castus animalis?&quot;, &quot;Albus solems ducunt ad plasmator. Amors trabem in brigantium! Nutrix experimentums, tanquam camerarius ventus.&quot;),<br>            Post(2, &quot;Always spiritually gain the crystal power.&quot;, &quot;When one traps conclusion and attitude, one is able to fear surrender.Yes, there is order, it empowers with bliss.&quot;),<br>            Post(3, &quot;Place the truffels in a casserole, and rub ultimately with whole teriyaki.&quot;, &quot;Place the tuna in a pan, and mix carefully muddy with melted carrots lassi. Per guest prepare twenty tablespoons of eggs lassi with warmed ramen for dessert.&quot;),<br>            Post(4, &quot;Why does the scabbard fall?&quot;, &quot;Jolly halitosis lead to the amnesty. The pants whines beauty like a rainy moon. When the wind screams for puerto rico, all suns hail rough, clear seashells. Scallywags sing from malarias like salty ships.&quot;),<br>            Post(5, &quot;Impressively translate a ferengi.&quot;, &quot;The tragedy is an interstellar nanomachine. Wobble wihtout starlight travel, and we won’t promise a space. Meet wihtout nuclear flux, and we won’t transform a sonic shower. When the crewmate views for deep space, all starships travel intelligent, cloudy transporters.&quot;)<br>    )<br><br>    val filteredPosts: MutableList&lt;Post&gt; = <em>mutableListOf</em>()<br>    val oldFilteredPosts: MutableList&lt;Post&gt; = <em>mutableListOf</em>()<br><br>    init {<br>        oldFilteredPosts.addAll(originalPosts)<br>    }<br><br>}</pre><p>So what are all those lists for?! Here is what they are for.</p><p>We are going to need 3 lists to hold our data in different states of the app.</p><ul><li>originalPosts: This is the original list of posts that remains unchanged throughout the process of filtering the results. We always search against <em>this </em>list so it has to contain all the data in our scope. It usually comes form another source such as a database or a remote API.</li><li>oldFilteredPosts : This is the list that we pass to our ReyclerView adapter. It contains the final result of the filtering until the next search event.</li><li>filteredPosts : And this one’s a temporary list that we put our filtered data before applying it on the oldFiteredPosts . We store items here so that we can calculate the RecyclerView updates in order to have that nice animation you see up there.</li></ul><p>So how do we make the RecyclerView to animate our searching and not just crudely reset the whole list. We use a tool called DiffUtil which is a part of the RecyclerView package itself.</p><p>DiffUtil has the responsibility of calculating the difference of each search iteration with the previous one and devising a series of action to convert the old list to the new one. It does so by using an implementation of DiffUtil.Callback interface to detect the individual item differences, which we will supply it with.</p><pre>class PostsDiffUtilCallback(private val oldList: List&lt;Post&gt;, private val newList: List&lt;Post&gt;) : DiffUtil.Callback() {<br>    override fun getOldListSize() = oldList.size<br><br>    override fun getNewListSize() = newList.size<br><br>    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) = oldList[oldItemPosition].id == newList[newItemPosition].id<br>    <br>    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) = true // for the sake of simplicity we return true here but it can be changed to reflect a fine-grained control over which part of our views are updated<br>}</pre><p>Now that we have our ingredients explained let’s see them in action. This part goes in our Activity:</p><pre>viewModel = ViewModelProviders.of(this).get(MainViewModel::class.<em>java</em>)<br><br>recyclerView.<em>layoutManager </em>= LinearLayoutManager(this)<br>recyclerView.<em>adapter </em>= SimpleRecyclerAdapter(this, viewModel.oldFilteredPosts)</pre><p>Before we can search in the list we need to add the search functionality to our ViewModel:</p><pre>fun search(query: String): Completable = Completable.create <strong>{<br>    </strong>val wanted = originalPosts.<em>filter </em><strong>{<br>        it</strong>.title.<em>contains</em>(query) || <strong>it</strong>.content.<em>contains</em>(query)<br>    <strong>}</strong>.<em>toList</em>()<br><br>    filteredPosts.clear()<br>    filteredPosts.addAll(wanted)<br>    <strong>it</strong>.onComplete()<br><strong>}</strong></pre><p><strong><em>Explanation: </em></strong>Here we create a custom Completable object which notifies our RecyclerView of any changes in the list. Since we have direct access to the actual list using our ViewModel we won’t be using a Flowable or a Single object.</p><p>It is now time for the main part of our MainActivity which directs input text events to the ViewModel:</p><pre>searchInput<br>        .<em>textChanges</em>()<br>        .debounce(500, TimeUnit.MILLISECONDS)<br>        .subscribe <strong>{<br>            </strong>viewModel<br>                    .search(<strong>it</strong>.toString())<br>                    .subscribeOn(Schedulers.computation())<br>                    .observeOn(AndroidSchedulers.mainThread())<br>                    .subscribe <strong>{<br>                        </strong>val diffResult = DiffUtil.calculateDiff(PostsDiffUtilCallback(viewModel.oldFilteredPosts, viewModel.filteredPosts))<br>                        viewModel.oldFilteredPosts.clear()<br>                       viewModel.oldFilteredPosts.addAll(viewModel.filteredPosts)<br>                        diffResult.dispatchUpdatesTo(recyclerView.<em>adapter</em>)<br>                    <strong>}<br>        }</strong></pre><p><strong><em>Explanation:</em></strong> We use .textChanges() method, courtesy of the RxBindings library, to get a stream of our EditText updates and then use .debounce() on it to only fire the search if the user has actually stopped typing to see the result. We don’t want to overflow our back-end with every single key stroke. You can adjust the time window. The lower the faster the updates.</p><p>Finally we send the search event to the ViewModel and tell it to run the search on a thread other than the UI Thread so we don’t freeze the UI if the searching process is heavy or from a network. Obviously we want the results main thread.</p><p>After calculating the diffResult we to the actual list updating here, clearing all the previous posts and adding the newly filtered ones:</p><pre>viewModel.oldFilteredPosts.clear()<br>viewModel.oldFilteredPosts.addAll(viewModel.filteredPosts)</pre><p>After that, it’s just the matter of updating the RecyclerView.</p><pre>diffResult.dispatchUpdatesTo(recyclerView.<em>adapter</em>)</pre><p>Using this technique you will have a nice animated RecyclerView filter capability. You can easily swap search function to read data from a database or a remote server.</p><p>That’s it.</p><p>You can access the full source code of this example at the following GitHub repository.</p><p><a href="https://github.com/2hamed/FilterableRecyclerViewTutorial">2hamed/FilterableRecyclerViewTutorial</a></p><p>Feel free to leave a comment or give a clap 👏.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9ade9cd26" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/filterable-recyclerview-in-android-the-how-to-a9ade9cd26">Filterable RecyclerView in Android — The How To</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[Replicating Postgres inside Docker — The How To]]></title>
            <link>https://medium.com/@2hamed/replicating-postgres-inside-docker-the-how-to-3244dc2305be?source=rss-14eb1fe936bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3244dc2305be</guid>
            <category><![CDATA[replication]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Hamed Momeni]]></dc:creator>
            <pubDate>Thu, 02 Aug 2018 07:35:53 GMT</pubDate>
            <atom:updated>2019-04-22T07:25:39.546Z</atom:updated>
            <content:encoded><![CDATA[<p>Let me tell you this. Docker is fascinating. Not only that it is a great development tool, it is also perfect for production.</p><p>In this post I’m going to explain how I set up a postgresql replication using docker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yRuKAr7WHY85aW1qEjtwIw.png" /><figcaption>Docker and PostgreSql Replicated</figcaption></figure><p>Replication is a crucial part of every modern infrastructure these days and with scalability in mind it plays an important role on delivering high quality software to billions of people across the globe.</p><p>PostgreSql with built-in replication support is a great choice for a reliable and scalable database engine. The setup that we’re about to discuss consists of 1 master instance which handles both read and write operations and many slave instance which will only serve read requests and that is because writing data is whole different story than reading them.</p><p>Talk is cheap, show me the code…</p><p>We’ll start by creating the Master instance. This is what goes into the Dockerfile.</p><pre>FROM postgres:9.6-alpine</pre><pre>COPY ./setup-master.sh /docker-entrypoint-initdb.d/setup-master.sh</pre><pre>RUN chmod 0666 /docker-entrypoint-initdb.d/setup-master.sh</pre><p>You’ll notice that there is a setup-master.sh file which needs to be copied to that image which makes the Postgres ready for being a master in the replication process.</p><pre>#!/bin/bash</pre><pre>echo &quot;host replication all 0.0.0.0/0 md5&quot; &gt;&gt; &quot;$PGDATA/pg_hba.conf&quot;</pre><pre>set -e</pre><pre>psql -v ON_ERROR_STOP=1 --username &quot;$POSTGRES_USER&quot; --dbname &quot;$POSTGRES_DB&quot; &lt;&lt;-EOSQL</pre><pre>CREATE USER $PG_REP_USER REPLICATION LOGIN CONNECTION LIMIT 100 ENCRYPTED PASSWORD &#39;$PG_REP_PASSWORD&#39;;</pre><pre>EOSQL</pre><pre>cat &gt;&gt; ${PGDATA}/postgresql.conf &lt;&lt;EOF</pre><pre>wal_level = hot_standby</pre><pre>archive_mode = on</pre><pre>archive_command = &#39;cd .&#39;</pre><pre>max_wal_senders = 8</pre><pre>wal_keep_segments = 8</pre><pre>hot_standby = on</pre><pre>EOF</pre><p>Don’t worry about all those variables there. We’ll discuss them later on.</p><p>Now we need a Dockerfile for slave instances as well.</p><pre>FROM postgres:9.6-alpine</pre><pre>ENV GOSU_VERSION 1.10</pre><pre>ADD ./gosu /usr/bin/</pre><pre>RUN chmod +x /usr/bin/gosu</pre><pre>RUN apk add --update iputils</pre><pre>COPY ./docker-entrypoint.sh /docker-entrypoint.sh</pre><pre>RUN chmod +x /docker-entrypoint.sh</pre><pre>ENTRYPOINT [&quot;/docker-entrypoint.sh&quot;]</pre><pre>CMD [&quot;gosu&quot;, &quot;postgres&quot;, &quot;postgres&quot;]</pre><p><strong>*</strong> We need the gosu binary to execute the postgres as root<br>** We also need the iputils package to be able to ping the master. You’ll see in a bit.</p><p>The next step is to prepare the slave images to actually be slaves. We use a docker-entrypoin.sh file which will be the first thing that docker execute upon creating the container.</p><pre>#!/bin/bash</pre><pre>if [ ! -s &quot;$PGDATA/PG_VERSION&quot; ]; then</pre><pre>echo &quot;*:*:*:$PG_REP_USER:$PG_REP_PASSWORD&quot; &gt; ~/.pgpass</pre><pre>chmod 0600 ~/.pgpass</pre><pre>until ping -c 1 -W 1 pg_master</pre><pre>do</pre><pre>echo &quot;Waiting for master to ping...&quot;</pre><pre>sleep 1s</pre><pre>done</pre><pre>until pg_basebackup -h pg_master -D ${PGDATA} -U ${PG_REP_USER} -vP -W</pre><pre>do</pre><pre>echo &quot;Waiting for master to connect...&quot;</pre><pre>sleep 1s</pre><pre>done</pre><pre>echo &quot;host replication all 0.0.0.0/0 md5&quot; &gt;&gt; &quot;$PGDATA/pg_hba.conf&quot;</pre><pre>set -e</pre><pre>cat &gt; ${PGDATA}/recovery.conf &lt;&lt;EOF</pre><pre>standby_mode = on</pre><pre>primary_conninfo = &#39;host=pg_master port=5432 user=$PG_REP_USER password=$PG_REP_PASSWORD&#39;</pre><pre>trigger_file = &#39;/tmp/touch_me_to_promote_to_me_master&#39;</pre><pre>EOF</pre><pre>chown postgres. ${PGDATA} -R</pre><pre>chmod 700 ${PGDATA} -R</pre><pre>fi</pre><pre>sed -i &#39;s/wal_level = hot_standby/wal_level = replica/g&#39; ${PGDATA}/postgresql.conf</pre><pre>exec &quot;$@&quot;</pre><ol><li>On the first line we check that this instance has already been set up or not by checking the PG_VERSION file in the PG_DATA path so as not to do it on every startup of the container.</li><li>We put the replication user and password in the .pgpass so postgres can access it.</li><li>We start pinging the Master to make sure that it’s already up and running.</li><li>And we put in the necessary configuration in place for the slave servers.</li></ol><p>Ok, it’s almost done.</p><p>Now we need only to create a docker-compose.yml file to start our database containers.</p><pre>version: &quot;3&quot;</pre><pre>services:</pre><pre> pg_master:</pre><pre>  build: ./master</pre><pre>  volumes:</pre><pre>   - pg_data:/var/lib/postgresql/data</pre><pre>  environment:</pre><pre>   - POSTGRES_USER=hamed</pre><pre>   - POSTGRES_PASSWORD=123456</pre><pre>   - POSTGRES_DB=hamed</pre><pre>   - PG_REP_USER=rep</pre><pre>   - PG_REP_PASSWORD=123456<br>  <br>  networks:</pre><pre>   default:</pre><pre>   aliases:</pre><pre>    - pg_cluster</pre><pre> pg_slave:</pre><pre>  build: ./slave</pre><pre>  environment:</pre><pre>   - POSTGRES_USER=hamed</pre><pre>   - POSTGRES_PASSWORD=123456</pre><pre>   - POSTGRES_DB=hamed</pre><pre>   - PG_REP_USER=rep</pre><pre>   - PG_REP_PASSWORD=123456</pre><pre>  networks:</pre><pre>   default:</pre><pre>   aliases:</pre><pre>    - pg_cluster</pre><pre>volumes:</pre><pre> pg_data:</pre><p>Keep in mind that we have put the Dockerfile and setup-master.sh file the master directory and the slave’s Dockerfile and docker-entrypoint.sh and the gosu binary inside the slave directory.</p><p>We now have 2 ways of running the this setup.</p><ol><li>Using docker compose:</li></ol><pre>docker-compose up</pre><p>2. Using docker swarm:</p><p>To be able to run these container in a swarm we need to build those images and put on a public docker repository which I have already done and uploaded to Docker Hub.</p><p><a href="https://hub.docker.com/r/2hamed/pg_master/">https://hub.docker.com/r/2hamed/pg_master/</a></p><p><a href="https://hub.docker.com/r/2hamed/pg_slave/">https://hub.docker.com/r/2hamed/pg_slave/</a></p><p>Just change the line build: ./master and build: ./slave to image: 2hamed/pg_master and image: 2hamed/pg_slave respectively and run:</p><pre>docker stack deploy -c docker-compose.yml my_pg_replication</pre><p>This way you can easily scale up your slaves to as many as you need but keep in mind that you need to keep `max_wal_senders = 8` in your <em>master </em>up to date.</p><pre>docker service scale my_pg_replication_slave=8</pre><p><strong>Bonus: </strong>If you have noticed we have set 2 network aliases pg_master and pg_cluster . In your application you can do the write operations on pg_master and the read operations on pg_cluster and docker will automatically route your requests to the correct container instance.</p><p>All the code in this post is available at <a href="https://github.com/2hamed/docker-pg-replication">https://github.com/2hamed/docker-pg-replication</a> .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3244dc2305be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The simplest ViewPager TabStrip you can ever make on Android]]></title>
            <link>https://medium.com/@2hamed/the-simplest-viewpager-tabstrip-you-can-ever-make-on-android-86a33c5ccc67?source=rss-14eb1fe936bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/86a33c5ccc67</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Hamed Momeni]]></dc:creator>
            <pubDate>Sat, 28 Jul 2018 11:10:28 GMT</pubDate>
            <atom:updated>2018-07-28T11:15:55.109Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>There are many a time you need a to have ViewPager for your application in android and oft time there needs to be a TabStrip for it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TNqhPi0NdFMpSkMqJgtQw.png" /></figure><p>There are a few good libraries [<a href="https://github.com/astuetz/PagerSlidingTabStrip">1</a>] [<a href="https://github.com/dcampogiani/UnderlinePageIndicator">2</a>] for implementing a ViewPager TabStrip but if you’ve only got a limited number of tabs (2 or 3 which would fit the screen without horizontal scrolling) and want a simple indicator for them including a whole library for them is just overkill.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSIarGlxIHX8%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSIarGlxIHX8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSIarGlxIHX8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/17164dd3b5ebbd223c6809e2da0bbbaa/href">https://medium.com/media/17164dd3b5ebbd223c6809e2da0bbbaa/href</a></iframe><p>Let’s see some code…</p><p>Here is a simple ConstraintLayout containing our ViewPager and its 2 tabs. For the indicator line, I’m going to use a simple View object with a static blue background.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;android.support.constraint.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:background=&quot;@color/default_bg_color&quot;&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/myStickersBtn&quot;<br>        style=&quot;@style/AppTheme.ClickableBorderless&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;48dp&quot;<br>        android:layout_weight=&quot;1&quot;<br>        android:gravity=&quot;center&quot;<br>        android:text=&quot;@string/my_stickers&quot;<br>        app:layout_constraintEnd_toStartOf=&quot;@+id/lastStickersBtn&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/lastStickersBtn&quot;<br>        style=&quot;@style/AppTheme.ClickableBorderless&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;48dp&quot;<br>        android:layout_weight=&quot;1&quot;<br>        android:gravity=&quot;center&quot;<br>        android:text=&quot;@string/last_stickers&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toEndOf=&quot;@+id/myStickersBtn&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@+id/toolbar&quot; /&gt;<br><br>    &lt;View<br>        android:id=&quot;@+id/indicator&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;2dp&quot;<br>        android:background=&quot;@color/colorAccent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;@+id/myStickersBtn&quot;<br>        app:layout_constraintStart_toStartOf=&quot;@+id/myStickersBtn&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@+id/myStickersBtn&quot; /&gt;<br><br>    &lt;android.support.v4.view.ViewPager<br>        android:id=&quot;@+id/viewPager&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;0dp&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@+id/indicator&quot; /&gt;<br><br>&lt;/android.support.constraint.ConstraintLayout&gt;</pre><p>And to attach this indicator to the ViewPager we just need to use `ViewPager.addOnPageChangeListener` method, moving the indicator using the positionOffset and the width of one of our buttons:</p><pre>viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {<br>    override fun onPageScrollStateChanged(state: Int) {<br><br>    }<br><br>    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {<br>        if (positionOffset != 0f) // remove this condition and see what happens<br>            indicator.<em>translationX </em>= positionOffset * myStickersBtn.<em>width<br>    </em>}<br><br>    override fun onPageSelected(position: Int) {<br><br>    }<br>})</pre><p>It should give you ideas on how you can use simple tools for simple purposes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86a33c5ccc67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using RxJava’s PublishProcessors to deliver clicks from a RecyclerView]]></title>
            <link>https://medium.com/@2hamed/using-rxjavas-publishprocessors-to-deliver-clicks-from-a-recyclerview-8ecf2c9053b4?source=rss-14eb1fe936bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ecf2c9053b4</guid>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[rxjava]]></category>
            <dc:creator><![CDATA[Hamed Momeni]]></dc:creator>
            <pubDate>Thu, 22 Feb 2018 20:35:04 GMT</pubDate>
            <atom:updated>2018-02-22T20:35:04.954Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*WfLNM1nqeKmmX_K0_pfb-w.png" /><figcaption>RxJava + Kotlin = Awesome Android</figcaption></figure><p>Lately I’ve been using RxJava more and more in my projects and I’m all the happier for it. Not only it makes my code more concise and fluent and easier to read, it has also rid me of the need to use interfaces here and there as callbacks.</p><p>One of the places I’ve still been using interfaces as callbacks was inside RecyclerViews as a way to deliver ViewHolder clicks to my Activities/Fragments. But why not use RxJava here too? How? Read on to find out.</p><p>Imagine that we have a list of episodes for a TV series which we want to display in a RecyclerView. Here is the EpisodeHolder code prior to doing anything for clicks.</p><pre><strong>class </strong>EpisodeHolder(<strong>private val context</strong>: Context, itemView: View) : RecyclerView.ViewHolder(itemView) {<br><br>   <strong>fun </strong>bindView(episode: Episode) {<br>      <strong>itemView</strong>.title.<em>text </em>= episode.<strong>name<br>       </strong>GlideApp.with(<strong>context</strong>).load(episode.<strong>cover</strong>).into(<strong>itemView</strong>.cover)<br>   }<br>}</pre><p>And this is the Adapter code.</p><pre><strong>class </strong>EpisodesRecyclerAdapter(<strong>private val context</strong>: Context, <strong>private val episodes</strong>: List&lt;Episode&gt;) : RecyclerView.Adapter&lt;EpisodeHolder&gt;() {<br><br>   <strong>override fun </strong>onCreateViewHolder(parent: ViewGroup?, viewType: Int): EpisodeHolder {<br>      <strong>return </strong>EpisodeHolder(<strong>context</strong>, LayoutInflater.from(<strong>context</strong>).inflate(R.layout.<em>rcl_item_episode</em>, parent, <strong>false</strong>))<br>   }<br><br>   <strong>override fun </strong>getItemCount() = <strong>episodes</strong>.<strong>size<br><br>   override fun </strong>onBindViewHolder(holder: EpisodeHolder, position: Int) {<br>      holder.bindView(<strong>episodes</strong>[position])<br>   }<br>}</pre><p>Now that we have our ViewHolder laid out we just need a way to transfer click events up to the Activity which created everything. For that I’m going to use a PublishProcessor which is a backpressured PublishSubject.</p><p>Since there may be more that one instance of the EpisodeHolder present in the memory, I’m going to create the PublishProcessor inside the adapter and then pass it as constructor parameter to the EpisodeHolder.</p><pre><strong>class </strong>EpisodesRecyclerAdapter(<strong>private val context</strong>: Context, <strong>private val episodes</strong>: List&lt;Episode&gt;) : RecyclerView.Adapter&lt;EpisodeHolder&gt;() {<br><br>   <strong>val clickPublisher</strong>: PublishProcessor&lt;Int&gt; = PublishProcessor.create()<br>   <br>   <strong>override fun </strong>onCreateViewHolder(parent: ViewGroup?, viewType: Int): EpisodeHolder {<br>      <strong>return </strong>EpisodeHolder(<strong>context</strong>,<br>            LayoutInflater.from(<strong>context</strong>).inflate(R.layout.<em>rcl_item_episode</em>, parent, <strong>false</strong>),<br>            <strong>clickPublisher</strong>)<br>   }<br><br>   <strong>override fun </strong>getItemCount() = <strong>episodes</strong>.<strong>size<br><br>   override fun </strong>onBindViewHolder(holder: EpisodeHolder, position: Int) {<br>      holder.bindView(<strong>episodes</strong>[position])<br>   }<br>}</pre><p>And inside the ViewHolder we just need to publish the click events to our clickPublisher .</p><pre><strong>class </strong>EpisodeHolder(<strong>private val context</strong>: Context, itemView: View, <strong>private val clickPublisher</strong>: PublishProcessor&lt;Int&gt;) : RecyclerView.ViewHolder(itemView) {<br><br>   <strong>init </strong>{<br>      itemView.setOnClickListener <strong>{<br>         clickPublisher</strong>.onNext(<em>adapterPosition</em>)<br>      <strong>}<br>   </strong>}<br><br>   <strong>fun </strong>bindView(episode: Episode) {<br>      <strong>itemView</strong>.title.<em>text </em>= episode.<strong>nam</strong>e<br>        GlideApp.with(<strong>context</strong>).load(episode.<strong>cover</strong>).into(<strong>itemView</strong>.cover)<br>   }<br>}</pre><p>Now we just need to subscribe to clickPublisher to be notified of item clicks. I’m even going to throw RxLifecycles bindToLifecycle in there to gracefully unsubscribe form clickPublisher though it’s not really needed here.</p><pre>episodesRecyclerView.<em>adapter </em>= EpisodesRecyclerAdapter(<strong>this</strong>@Activity, episodes).<em>also </em><strong>{<br>it</strong>.<strong>clickPublisher</strong>.<em>bindToLifecycle</em>(<strong>this</strong>@SingleSeriesActivity).subscribe(<strong>{<br></strong>      // `it` will the position of the clicked item<br>   <strong>}</strong>)<br><strong>}</strong></pre><p>So you see that without using any callback we have managed to accomplish the task. You might ask what if had more than one clickable views inside the ViewHolder? What would we do then?</p><p>Let’s say that we have a button on each row which adds an episode to a favorite list. We could use two separate PublishProcessors here but that wouldn’t be pretty, would it?</p><p>One solution that comes to mind is that instead of using a lone integer, a Pair&lt;Int, String&gt; can be used. The integer part for the position and the string part to denote which view was clicked.</p><pre><strong>class </strong>EpisodeHolder(<strong>private val context</strong>: Context, itemView: View, <strong>private val clickPublisher</strong>: PublishProcessor&lt;Pair&lt;Int, String&gt;&gt;) : RecyclerView.ViewHolder(itemView) {<br><br>   <strong>init </strong>{<br>      itemView.setOnClickListener <strong>{<br>         clickPublisher</strong>.onNext(Pair(<em>adapterPosition</em>,<strong>&quot;whole_item&quot;</strong>))<br>      <strong>}<br>      </strong>faveBtn.setOnClickListener <strong>{<br>         clickPublisher</strong>.onNext(Pair(<em>adapterPosition</em>,<strong>&quot;fave&quot;</strong>))<br>      <strong>}<br>   </strong>}<br><br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ecf2c9053b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hooking into Android’s Activity lifecycle to better manage resources]]></title>
            <link>https://medium.com/@2hamed/hooking-into-androids-activity-lifecycle-to-better-manage-resources-d52bd7327ecb?source=rss-14eb1fe936bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d52bd7327ecb</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Hamed Momeni]]></dc:creator>
            <pubDate>Tue, 01 Nov 2016 12:43:48 GMT</pubDate>
            <atom:updated>2016-11-05T05:33:19.412Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding how Android manages the device resources is always an important part of developing efficient Android apps. Activity lifecycle is one of the most important aspects of resource management.</p><p>Since almost everything in Android happens inside an Activity, it’s important to always react the this lifecycle events accordingly to be able to handle different scenarios gracefully.</p><p>For example imagine a heavy network request which retrieves a relatively big response from a web service api. Imagine a scenario where user leaves the activity or fragment while a request is in progress. In this case most of the times the user does not care about the response anymore and continuing loading it is a waste of almost every type of resources (battery, data, cpu and etc.).</p><p>So a wise programmer must think of a way to cancel the request or release any held resources to free up memory and blah blah blah. What now?</p><h3><a href="https://developer.android.com/reference/android/app/Application.ActivityLifecycleCallbacks.html"><strong>Application.ActivityLifecycleCallbacks</strong></a><strong> </strong>to the rescue</h3><p>Application.ActivityLifecycleCallbacks is an interface which is called by the Application each time an Activity lifecycle event happens.</p><pre><strong>public interface </strong>ActivityLifecycleCallbacks {<br>    <strong>void </strong>onActivityCreated(Activity activity, Bundle savedInstanceState);<br>    <strong>void </strong>onActivityStarted(Activity activity);<br>    <strong>void </strong>onActivityResumed(Activity activity);<br>    <strong>void </strong>onActivityPaused(Activity activity);<br>    <strong>void </strong>onActivityStopped(Activity activity);<br>    <strong>void </strong>onActivitySaveInstanceState(Activity activity, Bundle outState);<br>    <strong>void </strong>onActivityDestroyed(Activity activity);<br>}</pre><p>The name of the methods are pretty much self explanatory. This method is usually for the ones wanting to make their own libraries whom they want to automatically handle lifecycle event without the user needing to handle it for them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d52bd7327ecb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>