<?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 Minh Nguyen on Medium]]></title>
        <description><![CDATA[Stories by Minh Nguyen on Medium]]></description>
        <link>https://medium.com/@mikenguyenvan?source=rss-44dc79573610------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*lvIJrS6e3_0FBOeOt5jmdw.jpeg</url>
            <title>Stories by Minh Nguyen on Medium</title>
            <link>https://medium.com/@mikenguyenvan?source=rss-44dc79573610------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 16:02:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mikenguyenvan/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[It is 2020. I still write a topic about converting Android callback API to Rxjava stream]]></title>
            <link>https://medium.com/@mikenguyenvan/it-is-2020-i-still-write-a-topic-about-converting-android-callback-api-to-rxjava-stream-976874ebc4f0?source=rss-44dc79573610------2</link>
            <guid isPermaLink="false">https://medium.com/p/976874ebc4f0</guid>
            <category><![CDATA[android-location]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[location-based-services]]></category>
            <category><![CDATA[location]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Minh Nguyen]]></dc:creator>
            <pubDate>Sun, 09 Feb 2020 13:40:03 GMT</pubDate>
            <atom:updated>2020-02-10T15:52:08.534Z</atom:updated>
            <content:encoded><![CDATA[<h3>Re:Callback to Reactive (RxJava)</h3><p>I never write any blog posts, but seeing many of my colleges wrote their blogs and built their open-sources, encouraging me to choose a topic to start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Si8UBMzVq-p3dEndSPiQJw.png" /></figure><h4>Why do I choose an old topic to start</h4><p>Nowadays, everyone keeps talking about Kotlin Coroutine with Channels, Flow, and so on. But until now, the beginning of 2020, RxJava still a potent tool for building Android apps that I have not found any alternative. Flow may be a good option in the feature, but not at this moment. And I still see inadequate approaches from others when they create reactive objects. Especially when they use <strong>Observable.create</strong>() method. I could list some of them:</p><ul><li>Use the Subject instead create an Observable. <a href="http://tomstechnicalblog.blogspot.com/2016/03/rxjava-problem-with-subjects.html">This is a good topic</a> regarding the problem with subjects from Thomas Nield</li><li>Does not call onComplete/onError/tryOnError when using the <strong>Observable.create</strong> factory method to create Observable or Flowable which could lead to leaking</li><li>Does not care about threading when using “create”, what if the client calls “subscribeOn”.</li><li>Execute the logic outside of the factories method, which causes the logic being executed before the reactive stream being subscribe.</li><li>It does not use the power of Rxjava operation to build a clean Rxjava API. Mix the logic to convert Android API to Rxjava with the UI</li></ul><p><strong>How to create an Observable/Single/Flowable/Completable</strong></p><p>As many of you may know that we can create observable via multiple factory methods.</p><pre>Observable.fromCallable()<br>Observable.fromPublisher()<br>Observable.fromFuture()<br>Observable.fromArray()<br>Observable.just()<br>Observable.fromIterable()<br>Observable.defer()<br>...</pre><p>It recommended using these methods, if possible. There are a lot of great posts about this topic on the Internet, and I should not talk about them here. What I will focus on this post are:</p><ul><li>Convert Android callback-style API to the reactive world with <strong>Observable.create()</strong> method</li><li>Use Rxjava operations to design a clean API</li></ul><p>Let’s see an example of converting location API from Android &amp; Google Play Service to RxJava stream. I choose this example because it is complicated enough to present the solution to have a clean API.</p><p><strong>TL;DR: <em>you can check out the source code in this post from </em></strong><a href="https://github.com/roscrazy/android-rx-location"><strong><em>here</em></strong></a></p><p><strong>How to get location from Android</strong></p><p>For Android devices have Google Play Service, we can fetch the location or observe location change from two sources:</p><ul><li>Google Play Service (<a href="https://developers.google.com/location-context/fused-location-provider">Fused Location Provider API</a>)</li><li>Android API, that is <a href="https://developer.android.com/reference/kotlin/android/location/LocationManager">LocationManager</a></li></ul><p>These two sources provide us the locations with the callback API. To convert to a reactive stream, we have to use <strong>Observable.create()</strong> method.</p><p><strong>Let define the API that we want to build.</strong></p><p>Most of the apps request locations for two scenarios.</p><ul><li>Getting the last known location, you can check more detail <a href="https://developer.android.com/training/location/retrieve-current">here</a></li><li>Listen to the location change, you can check more detail <a href="https://developer.android.com/training/location/receive-location-updates.html">here</a></li></ul><p>From that requirement, we build this simple interface</p><pre>interface RxLocationManager {<br>   fun singleLocation(): Single&lt;Location&gt;<br>   fun observeLocationChange(): Observable&lt;Location&gt;<br>}</pre><p>The interface has two methods:</p><pre>fun singleLocation(): Single&lt;Location&gt;</pre><p>This method will return a Single, which emits the last known location value. We get the last known location by</p><ul><li>If there is other(s) call to observe the location change from <strong>RxLocationManager</strong>, the last received location(a cache value)should be emitted</li><li>If there is no other call &amp; cached location value, we will fetch the last know location from our sources(either Google Play Service or LocationManager)</li></ul><pre>fun observeLocationChange(): Observable&lt;Location&gt;</pre><ul><li>Return an observable that will emit the location after some time if there are any observer subscribes to it (the period should be configurable)</li><li>It should be a <strong>hot Observable</strong>. Multiple observers should subscribe to the same observable and got the same emitted item.</li><li>The last emitted item should be cached. If there is a new observer subscribe to the observable, it will receive the cached location (if available) as the first item</li><li>The observable should cancel itself if all the observers are disposed</li><li>We can tell the observable to emit locations on a specific thread</li></ul><p><strong>The implementation detail</strong></p><p>First of all, as mentioned earlier, there are two sources of getting locations, from either Google Play Service or Android Location manager. They provide quite similar APIs. Therefore, I create another interface present for the location services (sources). Let call it LocationService</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/905128d21ce1fdf26a8319986186b187/href">https://medium.com/media/905128d21ce1fdf26a8319986186b187/href</a></iframe><p>The <strong>LocationService.requestLocationUpdates</strong>() method will return an Observable, which will emit the locations based on the RxLocationAttributes values. You can think of RxLocationAttributes as a configuration object tell to the location services what do we want. Let focus on the implementations.</p><p><strong>Implementation with FusedLocationProviderClient</strong></p><p>Google Play Service provides us with FusedLocationProviderClient. There are two main methods that we will call:</p><pre>FusedLocationProviderClient.getLastLocation()<br>FusedLocationProviderClient.requestLocationUpdates()</pre><p>I create <strong>FusedLocationService</strong> class to implement the <strong>LocationService</strong> interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a8ce9700e104dfcbb31a56ee85ef072/href">https://medium.com/media/4a8ce9700e104dfcbb31a56ee85ef072/href</a></iframe><p>Let focus on <strong>createLocationObservable</strong>() method.</p><ul><li>Fetch last known location from Google Play service and emit to the stream</li><li>Listen to locations change from Google Play Service and emit to the stream.</li></ul><p>Here, we create an <strong>Observable</strong> by passing an <strong>ObservableOnSubscribe</strong> implementation to the <strong>Observable.create</strong> method. Inside the <strong>ObservableOnSubscribe</strong>, we have to implement the <strong>ObservableOnSubscribe.subscribe</strong> method. This method will be called when we subscribe to the observable, it receives an <strong>ObservableEmitter</strong> that allows pushing events in a cancellation-safe manner.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16aca90dd4cbee83ac345046999818ba/href">https://medium.com/media/16aca90dd4cbee83ac345046999818ba/href</a></iframe><p>When creating an Observable from <strong>Observable.create</strong>, we should make sure:</p><ol><li>Clean up resources if the <strong>ObservableEmitter</strong> is<strong> </strong>canceled or disposed. To clean up, we have a two options, <strong>ObservableEmitter.setDisposable()</strong> or <strong>ObservableEmitter.setCancellable()</strong>. They are equivalence. The main differences are <strong>setCancellable</strong> will deliver the exceptions during clean up to <strong>RxJavaPlugins.onError(Throwable). </strong>For our case, it’s remove the <strong>LocationUpdatesListener </strong>from <strong>FusedLocationProviderClient</strong></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/daeda6bada2eccec1b9eddfd500a5678/href">https://medium.com/media/daeda6bada2eccec1b9eddfd500a5678/href</a></iframe><p>2. Catch the exception and make sure calling <strong>ObservableEmitter</strong><a href="http://reactivex.io/RxJava/javadoc/io/reactivex/ObservableEmitter.html#tryOnError-java.lang.Throwable-"><strong>.tryOnError()</strong></a><strong> </strong>or <strong>ObservableEmitter.onError() </strong>to pass the error to the stream. The main difference between these two methods is that <strong>ObservableEmitter.tryOnError</strong> will not forward the error to <strong>RxJavaPlugins.onError </strong>if the error could not be delivered.</p><pre><strong>try </strong>{<br>    // register the callback<br>} <strong>catch </strong>(e: Exception) {<br>    emitter.tryOnError(e)<br>}</pre><p>3. Make sure you call <strong>ObservableEmitter.onComplete</strong>() if the source finishes emitting the items(applicable for Observable &amp; Flowable) . For our example, it’s a hot observable, and we don’t have any complete points.</p><p>4. These methods <strong>ObservableEmitter.onNext()</strong>, <strong>ObservableEmitter.onError()</strong>, <strong>ObservableEmitter.tryOnError()</strong> and <strong>ObservableEmitter.onComplete()</strong> should be called in a sequential</p><p>5. What thread your observable will emit the value on. Most of the callback API provided will emit the value to the register thread (the thread execute the registration callback to the framwork) by default. In Android many callback API will requite an HandlerThread for the default register thread and also if you want to tell to the API to call the callback in another thread, then you have to pass a looper or an handler to the API. In our example you can see:</p><pre>fusedLocationProviderClient.requestLocationUpdates(<br>    getLocationRequest(attributes),<br>    listener,<br><strong>    if (attributes.useCalledThreadToEmitValue) null else Looper.getMainLooper()</strong><br>)</pre><p>Base on the <strong>attributes.useCalledThreadToEmitValue</strong>, we will pass a null value or the main looper to the method.</p><ul><li>Null value: The callback will be called from the thread, which executes the <strong>ObservableOnSubscribe.subscribe</strong> method. Usually, it will be the thread that you subscribe to the stream, or you can tell the observable to emit the value from which thread by <strong>subscribeOn(Thread)</strong>. Please be aware, in our case. The thread must be a HandlerThread, otherwise an exception is throwed. You can read more about HandlerThread <a href="https://blog.mindorks.com/android-core-looper-handler-and-handlerthread-bd54d69fe91a">here</a> or <a href="https://medium.com/mindorks/mastering-android-handler-4f710296bdc6">here</a>.</li><li>Looper.getMainLooper(): We default the callback will be called from the main thread. It means that the Observable will emit location from the main thread even you applied <strong>subscribeOn(Thread)</strong> to the stream.</li></ul><p>That is, regarding create the Observable by <strong>Observable.create</strong> method.</p><p>Let look more detail on the <strong>FusedLocationService.requestLocationUpdates</strong> method</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62c12eed2a84eca72b64643c3c67f5aa/href">https://medium.com/media/62c12eed2a84eca72b64643c3c67f5aa/href</a></iframe><p>We will retry the observable <strong>attribute.retryAttempt</strong> times, if any errors occurred excepts <strong>GooglePlayServicesNotAvailableException </strong>(Google play services is not available) or <strong>SecurityException</strong>(permission has not granted). Be aware that we can set <strong>attribute.retryAttempt </strong>via RxLocationAttributes.</p><p>So, with the same approach, I have an implementation to getting the location from Android API (LocationManager)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09707f25d798db982e1d3f211b35619e/href">https://medium.com/media/09707f25d798db982e1d3f211b35619e/href</a></iframe><p><strong>Implement the RxLocationManager interface</strong></p><p>Now it’s the time for us to integrate the two services, and implement the interface <strong>RxLocationManager</strong> that we designed at the beginning.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e67794d319234687568fd69734ac3f35/href">https://medium.com/media/e67794d319234687568fd69734ac3f35/href</a></iframe><p>Let look into <strong>RxLocationManagerImpl.createLocationObservable</strong> method</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba15c6fa272c8da395b304eb70dafc1d/href">https://medium.com/media/ba15c6fa272c8da395b304eb70dafc1d/href</a></iframe><p>First we will observe the location update from <strong>FusedLocationService</strong>, if there is any error occurred, we will switch to observe location change from <strong>AndroidLocationService</strong>. For example, if we run this piece of code in any Chinese devices without Google Play Service, then <strong>AndroidLocationService</strong> will be used.</p><p>Next, we apply replay and refCount operations</p><pre>fusedLocationService.requestLocationUpdates(locationAttributes)<br>    .onErrorResumeNext { it: Throwable -&gt;...}<strong><br>    .replay(1)<br>    .refCount()</strong></pre><ul><li>replay(1) turn the observable to a ConnectableObservable, the lastest item will be replay, if any new observer subscribe to the stream.</li><li>.refCount() make the ConnectableObservable behave like an ordinary Observable. RefCount then keeps track of how many other observers subscribe to it and does not disconnect from the underlying connectable Observable until the last observer has done so.</li></ul><p><em>So, in the end, our target only registers one callback to the API, even multiple observers subscribe to the Observable. And all observers should receive the same locations.</em></p><p>Let move to the <strong>RxLocationManager.singleLocation</strong> method</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82783574e9231da8b4a4d90ef6da07cc/href">https://medium.com/media/82783574e9231da8b4a4d90ef6da07cc/href</a></iframe><p>We reuse the observable from <strong>RxLocationManager.observeLocationChange()</strong> method, convert it to a single by calling <strong>Observable.firstOrError()</strong>. For this approach, we will benefit from the caching value from the <strong>observeLocationChange</strong> if there are any observers currently subscribe to the Observable. But the downside is if your app does not actively observe location change, and keep calling the <strong>singleLocation</strong> multiple times. We may consume more battery than expected. Because if there is no observer subscribe to the observable, then every time you call <strong>singleLocation</strong>, we will register the callback to location provides, which high chance will fire our device GPS or other tools.</p><p>Secondly, I add the option to set up a location request time out for <strong>singleLocation</strong>. Most of the time we call to get one single location, we expect to get it fast, and possibly there is delaying/hanging on getting the location. For that case, we should fire an error instead of keeping waiting. So, the downstream could show the user an error message.</p><p><em>That it, it’s very appreciate that you reach to this point of my post</em></p><p><em>As mention ealier, the source code is</em><a href="https://github.com/roscrazy/android-rx-location"><em> </em><strong><em>available here</em></strong></a><em>. I create a sample in the repo for you to play with the implementation, it’s recommended to check it out.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=976874ebc4f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>