<?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 Phạm Giang on Medium]]></title>
        <description><![CDATA[Stories by Phạm Giang on Medium]]></description>
        <link>https://medium.com/@giangp2901?source=rss-76adc0b4e2bc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4H1jSMwF3hvSde3N</url>
            <title>Stories by Phạm Giang on Medium</title>
            <link>https://medium.com/@giangp2901?source=rss-76adc0b4e2bc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:50:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@giangp2901/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[Implementing Search-on-type in Android with Coroutines]]></title>
            <link>https://medium.com/android-news/implementing-search-on-type-in-android-with-coroutines-ab117c8f13a4?source=rss-76adc0b4e2bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab117c8f13a4</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[searchview]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[debouncing]]></category>
            <dc:creator><![CDATA[Phạm Giang]]></dc:creator>
            <pubDate>Thu, 14 Mar 2019 07:21:23 GMT</pubDate>
            <atom:updated>2019-05-11T06:56:34.627Z</atom:updated>
            <content:encoded><![CDATA[<p>We have to agree, search-on-type has been a common feature in Android applications. The functionality requirement is pretty straight forward: the app starts searching as the user starts typing. However, the technical requirement is not so simple. The app should not search immediately when the text changes, but only after an interval. This saves more than 50% of requests if the Android client is fetching data from an API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TeUGN4lvQzYSTxLY.png" /><figcaption>The behaviour of the search view should be the same as debounce operator in ReactiveX</figcaption></figure><p>To achieve this, if a developer is using <em>RxJava</em> inside his/her project, he/she will be likely to use <em>RxAndroid</em> and <em>RxBinding</em>, and write a few easy lines of code. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e45c6548448c73bb10656707d3379d1/href">https://medium.com/media/1e45c6548448c73bb10656707d3379d1/href</a></iframe><p>Just easy as that.</p><p>But this is the case of <em>RxJava </em>projects. What about projects use another concurrency solutions such as <strong><em>Coroutines</em></strong>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*12vD1FpJ0na6jbj2.png" /></figure><p>In this piece of writing, I wouldn’t explain what is <em>Coroutines </em>or how to use it. I will only focus on how to make a debouncing search view with <em>Coroutines.</em></p><h4><strong>First attempt</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/956d49230d7d76f4e15fe28fdf00ddd4/href">https://medium.com/media/956d49230d7d76f4e15fe28fdf00ddd4/href</a></iframe><p>Here, I create an <em>OnQueryTextListener </em>implementation, which has a CoroutineScope<em> </em>with<em> </em>Main<em> </em>dispatcher and a Job (<em>searchJob</em>) variable. Whenever the text changes, the previous search is cancelled if it hasn’t been dispatched for more than a second, and a new search is launched.</p><p>Looks nice, isn’t it? But we can do it better. The code above is not reusable, which is not handy if the project has many search views. Trust me, there are applications with more than 3 search views in it.</p><h4><strong>Second attempt</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/537c12af5eb25f8ae19a2da15227de87/href">https://medium.com/media/537c12af5eb25f8ae19a2da15227de87/href</a></iframe><p>What we could do is to write a class that implements OnQueryTextListener, which requires a <em>lambda</em> as a property. That <em>lambda</em> acts like a <em>callback</em> and is invoked after the delay call <em>(line 19)</em>. This way, we make this <em>Listener</em> reusable and bring some clean code guidelines into the game, which is just awesome! Moreover, the debounce period is now adjustable by making it a property with public setter <em>(line 4)</em>. I am not sure if making it fixed in initialisation time or allowing it to be changed in runtime is better. For now, this doesn’t break anything. The code in the<em> Activity/Fragment </em>will become:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7695051df7906e04d889a702b8dbd5db/href">https://medium.com/media/7695051df7906e04d889a702b8dbd5db/href</a></iframe><p>But wait, adjustable debounce period is not so safe. Imagine if a guy sets it to 3 minutes (I know this is unrealistic, but it can happen theoretically), and the user probably doesn’t stay in that screen<em> (Activity/Fragment) </em>that long, why would we still dispatch the search? Let save some resource here.</p><p>How does the <em>Listener</em> even know if the <em>Activity</em> or <em>Fragment</em> is being destroyed? Luckily, <a href="https://developer.android.com/jetpack/androidx/releases/lifecycle"><strong>Lifecycle-aware components</strong></a><strong><em> </em></strong>are there to save the day.</p><h4>Final attempt!!!</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1205e9ec784c9a4168d82932990ae331/href">https://medium.com/media/1205e9ec784c9a4168d82932990ae331/href</a></iframe><p>Making the listener a LifecycleObserver, passing in a Lifecycle and observe it at initialisation time. Whenever the <em>lifecycle</em> is destroyed, perform a cancellation<em> (Line 33)</em>. Those are all the thing added above.</p><p>And here is how to use it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c02f55f8b214aff7e5cab29933699449/href">https://medium.com/media/c02f55f8b214aff7e5cab29933699449/href</a></iframe><p>I am not saying that this is the most effective way, at least, an extra dependency is required, and maybe this is a bit over-engineering. At the time writing this article, I use <em>ViewModel</em> and <em>LiveData</em> in my project, which comes with the <em>Lifecycle</em> stuff, that’s why I come up with the idea.</p><p>You can find the project <a href="https://github.com/giangpham96/omdb-client">here</a>. Thanks for reading!</p><h3>UPDATE</h3><p>In <a href="https://www.youtube.com/watch?v=BOHK_w09pVA">Google I/O’ 19</a>, <em>LifecycleCoroutineScope </em>is introduced. This even allows me to write even shorter <em>DebouncingQueryTextListener.</em> For example:</p><pre><strong>internal class </strong>DebouncingQueryTextListener(<br>    lifecycle: Lifecycle,<br>    <strong>private val onDebouncingQueryTextChange</strong>: (String?) -&gt; Unit<br>) : SearchView.OnQueryTextListener {<br>    <strong>var debouncePeriod</strong>: Long = 500<br><br>    <strong>private val coroutineScope </strong>= lifecycle.<em>coroutineScope<br><br>    </em><strong>private var searchJob</strong>: Job? = <strong>null<br><br>    override fun </strong>onQueryTextSubmit(query: String?): Boolean {<br>        <strong>return false<br>    </strong>}<br><br>    <strong>override fun </strong>onQueryTextChange(newText: String?): Boolean {<br>        <strong>searchJob</strong>?.cancel()<br>        <strong>searchJob </strong>= <strong>coroutineScope</strong>.<em>launch </em><strong>{<br>            </strong>newText?.<em>let </em><strong>{<br>                </strong><em>delay</em>(<strong>debouncePeriod</strong>)<br>                <strong>onDebouncingQueryTextChange</strong>(newText)<br>            <strong>}<br>        }<br>        return false<br>    </strong>}<br>}</pre><p>My coroutineScope becomes lifecycle.<em>coroutineScope </em>, it is nice that I no longer handle the clean up job, and the class no longer needs to extend LifecycleObserver . All I need is having lifecycle-runtime-ktx library inside my project. The usage stays the same. Another day, another trick. So glad to see that <em>coroutines first </em>attitude from Google.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab117c8f13a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/implementing-search-on-type-in-android-with-coroutines-ab117c8f13a4">Implementing Search-on-type in Android with Coroutines</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[Survive backend redeployment with a DNS failover OkHttp client]]></title>
            <link>https://medium.com/android-news/survive-backend-redeployment-with-a-dns-failover-okhttp-client-85cd0b302537?source=rss-76adc0b4e2bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/85cd0b302537</guid>
            <category><![CDATA[connection-pool]]></category>
            <category><![CDATA[keep-alive-connection]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[okhttp]]></category>
            <category><![CDATA[interceptors]]></category>
            <dc:creator><![CDATA[Phạm Giang]]></dc:creator>
            <pubDate>Sat, 22 Sep 2018 20:41:10 GMT</pubDate>
            <atom:updated>2018-11-05T09:32:21.656Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>The what</strong></h3><p>Recently, I was struggling with a problem that happens when back-end guys redeploy their web service. The problem was that after the new stack is ready, we started deleting the old stack, and my Android client application, which works continuously and perfectly in the previous 2 hours (it is an internal app, so it is used 15 hours a day without being closed), gets 503 response code constantly when trying to make calls to that service. I didn’t know why it happened, the endpoint doesn’t change, the new stack is there, and I get 200 response code if making the request with curl or Postman. The interesting part is that the Android client works normally only after 5 minutes of 503 panic… But for us, unfortunately, 5 minutes of outage is a total disaster.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FXumi4QKYocrLi%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2F503-Xumi4QKYocrLi&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FXumi4QKYocrLi%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="372" frameborder="0" scrolling="no"><a href="https://medium.com/media/3189a0181fa921bb4d1939b36f953ae2/href">https://medium.com/media/3189a0181fa921bb4d1939b36f953ae2/href</a></iframe><h3>The why</h3><p>Luckily, my Back-end guys are awesome enough to tell what happened. The guy to blame here is keep-alive connection.</p><p><strong>Briefly keep-alive connection explanation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/0*wCdSSIfuBymTYAXZ.png" /><figcaption>Keep-alive connection</figcaption></figure><p>Basically, when a client makes a request to the server with a <em>Connection: keep-alive</em> header, and the server replies with a response, which also has <em>Connection: keep-alive</em> header, the connection is kept alive, which means it will be reused in the future if the client make another request to the server. Of course, there is a life time for that connection, for example, 10 seconds after the response is received.</p><p><strong>Why is keep-alive connection related to the problem?</strong></p><p>As mentioned above, the connection is reused. Consequently, the client does not do any DNS look-up, it uses the same host IP address as previous requests. However, the new server has different IP address. Now you probably see the problem. After the old stack is deleted, the previous IP address is no longer a valid one, but the client keeps ‘harassing’ it until the connection is closed due to timeout. After that, a new connection is established and everything is back to normal. By default, OkHttp client possesses a <a href="https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/ConnectionPool.java">ConnectionPool</a> with keep-alive timeout of 5 minutes, which explains why my app got 503 for the exact same duration.</p><h3>The how</h3><p>In this section, I will only discuss on the client point of view. Maybe there is a way to fix that in server side or by editing AWS configuration, but let not mention it here (because I am not an expert in AWS sadly 😢).</p><p>OK, the quickest and easiest fix is not to use the keep-alive timeout. Problem solved. As they say, you don’t have to fix it if you don’t use it 😆 😆 😆</p><p>What if the app is required to get the response fast? As I said, it is an internal app, which is used by workers, employees, etc, so if the response time is faster, they also work faster, and the company gains benefits. My second attempt to solve the problem is very straight forward. If the client ever gets 503, it will close all idling connections (keep-alive connections which is not in used) and retry once (once only because I do not want the app to get in an endless loop, 503 may occur due to different reasons).</p><p>Enough theory, let dive into the code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcc9cdf258b212d166ba95a86da49abe/href">https://medium.com/media/fcc9cdf258b212d166ba95a86da49abe/href</a></iframe><p>The code explains itself quite clearly. I created an Interceptor which takes a ConnectionPool as a property inside the constructor. What connectionPool.evictAll() does is simply close all idling connections.</p><p>Where can I get the ConnectionPool to inject inside this fancy Interceptor?</p><p>Probably when I create the OkHttp client.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b7ee9382fb3098743ffe2e277fffc13/href">https://medium.com/media/0b7ee9382fb3098743ffe2e277fffc13/href</a></iframe><p>Above is my colleague’s awesome function to build OkHttp client. What I changed is that I define my own ConnectionPool and pass it to both the OkHttpClient.Builder(line 10) and the DNSFailOverInterceptor(line 13) after adding all other interceptors (yes, it must be the last one). In this piece of code, I used default ConnectionPool, which has keep-alive timeout of 5 minutes because I think it would not break anything in our project (obviously)😃. But if you want to, you can modify it as you want (ie. extend the timeout)</p><p>I also wrote unit tests for the interceptor to verify its logic, but I am not going to post it here. Let say it is your task if you find this piece of writing useful😃. Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85cd0b302537" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/survive-backend-redeployment-with-a-dns-failover-okhttp-client-85cd0b302537">Survive backend redeployment with a DNS failover OkHttp client</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>