<?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 Gabriel Sanmartín on Medium]]></title>
        <description><![CDATA[Stories by Gabriel Sanmartín on Medium]]></description>
        <link>https://medium.com/@kelmer?source=rss-ce83cb5ab103------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*nN_iANWh-JKf8_2eJRITFQ.png</url>
            <title>Stories by Gabriel Sanmartín on Medium</title>
            <link>https://medium.com/@kelmer?source=rss-ce83cb5ab103------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 08:27:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kelmer/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[Back to the basics: Android with no libraries (Part 2)]]></title>
            <link>https://medium.com/@kelmer/back-to-the-basics-android-with-no-libraries-part-2-6ad90428baca?source=rss-ce83cb5ab103------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ad90428baca</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-apps]]></category>
            <dc:creator><![CDATA[Gabriel Sanmartín]]></dc:creator>
            <pubDate>Thu, 14 May 2020 15:31:09 GMT</pubDate>
            <atom:updated>2020-05-14T15:31:09.689Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F4en87wbDqGjCIU2-8-2KQ.jpeg" /></figure><p>On the <a href="https://medium.com/@kelmer/back-to-the-basics-android-with-no-libraries-part-1-2bd8c5e5d725">previous article</a> we created a project to consume Flickr’s Photo Search API using a standard set of libraries, and then we started stripping those by removing Retrofit and Gson.</p><p>In this article we are gonna leave our app completely library free by removing implementing our own image fetching solution, and our own threading model to handle API requests (or any other task for that matter) in the background.</p><h4>Step 3: Removing Glide</h4><p>Now for the complicated part! Glide (or Picasso, or Fresco) does <strong>a lot</strong> of heavy lifting for us when it comes to loading images in the background, and implementing this won’t be as straightforward.</p><p>Essentially what we need is something that will request an image from a remote source and load it into a view and supporting multiple view targets — all the while doing all this in a background thread so the view isn’t blocked while the job is being performed.</p><p>At first this might seem a bit overwhelming: this involves a lot of weak referencing, dangerously playing with the lifecycle events (what if my <em>ImageView</em> is no longer there when my image is loaded?), and making sure everything happens with the right threading model.</p><p>Then I found <a href="https://www.androidhive.info/2012/07/android-loading-image-from-url-http/">this article</a> which gives a simple example and decided to base my implementation on that.</p><p>We will replicate Glide’s simplistic build api:</p><pre>GlideApp.<em>with</em>(<em>context</em>)<br>        .load(image.url)<br>        .placeholder(R.drawable.loading)<br>        .into(view);</pre><p>Into:</p><pre>ImageFetcher(<em>context</em>)<br>    .load(image.url,<br>        view,<br>        R.drawable.<em>loading</em>,<br>        imageHeight)</pre><p>What happens within the load method? Let’s take a look at the <a href="https://github.com/kelmer44/flickr-test/blob/master/app/src/main/java/net/kelmer/android/network/imagefetcher/ImageFetcher.kt">ImageFetcher</a> class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/813b02eb8b4dc59443f1f018e880844e/href">https://medium.com/media/813b02eb8b4dc59443f1f018e880844e/href</a></iframe><p>Every time we call the <em>load</em> method, we will be storing the target view into a <em>WeakHashmap</em> along with the target URL of the image:</p><pre>private val imageViews = Collections.synchronizedMap(WeakHashMap&lt;ImageView, String&gt;())</pre><pre>imageViews[imageView] = url</pre><p>A WeakHashMap is a HashMap which contains weak references to its keys. According to the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/WeakHashMap.html">official docs:</a></p><blockquote>The presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector</blockquote><p>If we used a regular <em>HashMap</em>, and then we started scrolling through our image based <em>RecyclerView</em>, we would be leaking all these <em>ImageViews</em> in memory, since the Garbage Collector wouldn’t be able to destroy those objects until we manually would clear them from our map.</p><p>After making sure to save our target view, we call <em>queuePhoto</em> with the necessary details to perform the job. As the name suggests, this function will put our Image fetching job into a queue to be addressed as soon as it can.</p><p>But remember, this is a network request and thus it needs to be done in a background thread. In order to do that, we will make use of the new <a href="https://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/">Java 8 Concurrency API</a>, based on <em>Executors</em>. In a nutshell, this API abstracts a little bit more the threading work by relying on <em>ExecutorServices</em>, which manage the thread pool for us and let us send in work in the form of <em>Runnables</em>.</p><p>Now at the top of our file we declared the following Executor Service:</p><pre>private val executorService = Executors.newFixedThreadPool(5)</pre><p>This means our thread pool will be comprised of 5 threads and thus we will be able to retrieve up to 5 images in parallel. And ExecutorService will handle that for us!</p><p>Let’s take a look at how its done:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09490f5b336b85a708f76784063922cb/href">https://medium.com/media/09490f5b336b85a708f76784063922cb/href</a></iframe><p><em>queuePhoto</em> is calling <em>submit</em> on our executor with a <em>Runnable</em> object, <em>ImageLoader</em>, who will do the long running operation of retrieving an image from the network.</p><p>The submit call is not blocking, and thus the execution of the program continues. After the <em>getBimap</em> operation is performed in a separate thread, ImageLoader needs to return its value to the UI to present it on the screen.</p><p>To do that, we created a Handler object and initialized it <a href="https://developer.android.com/reference/android/os/Looper"><em>Looper.getMainLooper()</em></a>, a utility method provided by Android that returns the UI thread. This gives us access to the main thread at any moment.</p><p>After the job is done, our <em>ImageLoader</em> sends a <em>Runnable</em> operation to this <em>Handler</em>, in the form of an instance of the <em>BitmapDisplayer</em> object. This class just receives a bitmap and puts it into our view like we would do normally:</p><pre>imageView.setImageBitmap(b)</pre><p>This, in all, is a reduced, simplified version of what Glide/Picasso or any major library is doing for us magically. If we check the <a href="https://github.com/bumptech/glide/blob/master/library/src/main/java/com/bumptech/glide/RequestBuilder.java">RequestBuilder.java</a> class on Glide, we can get a glimpse of all this, even if (of course) a bit more sophisticated.</p><p>Since this is a bit complicated to follow, here’s a diagram of what’s happening:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*g3gEteziscmzjpN0-fcstA.png" /><figcaption>Image Fetcher thread model</figcaption></figure><p>Now to that getBitmap method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6fa9300467c03d3591688e13ca20d91/href">https://medium.com/media/f6fa9300467c03d3591688e13ca20d91/href</a></iframe><p>Same as we did in the Retrofit replacement, we use <em>HttpUrlConnection</em> to perform a get request, only this time instead of converting its response into a String, we save it as a temp file (<em>copyStream</em> just takes chunks of bytes from <em>inputStream</em> and writes them into the <em>outputStream</em>).</p><p>Once the file is stored, we decode it into a Bitmap in the <em>decodeFile</em> function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b69193e4a09d09e3d00fbe73076fe741/href">https://medium.com/media/b69193e4a09d09e3d00fbe73076fe741/href</a></iframe><p>This function has two steps. Android provides a <em>BitmapFactory</em> object which allows low-level binary work with bitmaps and image transformations. The <em>decodeStream</em> basically turns a byte stream into valuable imaging information, generally the Bitmap itself.</p><p>But if you set the <em>inJustDecodeBounds </em>to <em>true</em>, then it only grabs the width and height information from that byte array and returns it. This is step 1. Why is this needed? If the image being downloaded would be huge (let’s say three times the screen size) then transforming it into a Bitmap would most likely result in an Out of Memory Exception, due to the total size being bigger than the Heap size Android allocates to our app.</p><p>So what we need to do is specify the desired size of the image for our app. Generally this size needs is determined based on the <em>ImageView</em> size on the screen. After all, why store in memory an image that is bigger than the region of the screen we will display it on?</p><p>This is what the line</p><pre>height.<em>coerceAtMost</em>(bmpHeight)</pre><p>does: It ensures that the size is the minimum between the specified height and the original height of the bitmap.</p><p>After calculating the resulting size, we go to step 2, which is calling decodeBitmap again without the <em>inJustDecodeBounds, </em>to effectively decode our image into a Bitmap that can be passed in directly to our <em>ImageView</em>.</p><p>But wait! What is the specified <em>height</em> that 7our function receives? Well one way to determine this size would be to get the calculated height of the original <em>ImageView</em> and pass it in as the max value of our image.</p><p>The problem with this is — many times, especially if we are working with <em>ImageView</em> within a <em>RecyclerView</em> <em>ViewHolders</em>, the size of the view is unknown by the time it reaches the <em>bind</em> method of our <em>ViewHolder</em>. So we would have to <strong>wait </strong>until this size is known and only then decode our Bitmap. This means putting all target ImageViews into a separate queue, set up a listener to see when they’ve been laid out, and then make sure to trigger the decode function again.</p><p>We can see how in <a href="https://github.com/bumptech/glide/blob/master/library/src/main/java/com/bumptech/glide/request/SingleRequest.java">SingleRequest.java</a>, Glide also has to do this: it has to wait for the size to be available before trying to retrieve and transform the image:</p><pre>if (Util.<em>isValidDimensions</em>(overrideWidth, overrideHeight)) {<br>  onSizeReady(overrideWidth, overrideHeight);<br>} else {<br>  target.getSize(this);<br>}</pre><p>However, for this scenario and for simplicity, I took a shortcut and made our load function include a height parameter to explicitly indicate the dimension of our desired <em>ImageView</em>. It’s not perfect, but hey, it gets the job done. It also illustrates how much are these image libraries doing for us!</p><p>We are crunching our dependency list and it now looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b88a2382fd27499e8563ae52d035a36e/href">https://medium.com/media/b88a2382fd27499e8563ae52d035a36e/href</a></iframe><p>you can find the source for this approach at <a href="https://github.com/kelmer44/flickr-test/tree/step3-no-glide">this branch</a></p><h4>Step 4: Removing Rx</h4><p>And the final step! So far we’ve been using RxJava2 to perform our REST requests in a background thread thanks to their great abstraction on threading using the <em>subscribeOn</em> and <em>observeOn</em> chain methods. It is time for us to replace this and do the threading ourselves!</p><blockquote>NOTE: RxJava is much more than just a threading handling solution, and in my opinion if this is the only problem it solves for you, there are simpler, lighter solutions out there (like coroutines).</blockquote><p>We will use the same threading mechanism we used for the Glide replacement: Java 8’s Executors.</p><p>Let’s start by recalling what our REST API consumer interface is declaring:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54f22f783e92046383729a0ddaa557b7/href">https://medium.com/media/54f22f783e92046383729a0ddaa557b7/href</a></iframe><p>So we will pass our search function a bunch of parameters and get an <em>ApiResponse</em> in return. But this is defined in a blocking manner: we are not instructing this code to be run in a background thread, thus if we just remove Rx and make our Repository look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/394ae90bd44fbad036c8578d274faacb/href">https://medium.com/media/394ae90bd44fbad036c8578d274faacb/href</a></iframe><p>We would be getting the infamous <a href="https://developer.android.com/reference/android/os/NetworkOnMainThreadException">NetworkOnMainThread</a> exception.</p><p>Hence, we want this code to be executed in a separate thread, and then come back with the results to the UI thread.</p><p>The naivest approach to do this with executors (aside from <em>AsyncTask</em> which we will avoid) would be to just put the executor calling code within our <em>Repository</em> or <em>Service</em> implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc544b1f1aa7f289f4f81537419bf7de/href">https://medium.com/media/dc544b1f1aa7f289f4f81537419bf7de/href</a></iframe><p>But this has some issues. First of all, it’s a bit clunky having to pass in an instance of our callback interface for every method that has to be run in the background. Second, and perhaps more important, the reference to that instance will be held by the <em>repository</em>/<em>service</em> class thus running the risk of creating a memory leak for the calling <em>view</em>/<em>viewModel</em> or updating an old UI.</p><p>So what if we abstract this code a little into a <em>Task</em> object, that can delegate the execution itself to the calling code in the <em>ViewModel</em> (which is already lifecycle aware)?</p><p>Incidentally, this is a similar approach to what vanilla Retrofit (with no adapters) does to create our REST consuming services, in the <a href="https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit2/Call.java">Call</a> class.</p><p>So we are going to define our <em>Task</em> interface, that has a <em>call</em> method returning a generic-typed object:</p><pre>interface Task&lt;T&gt; {<br>    fun call(): T<br>}</pre><p>We will still declare our <em>Callback</em> interface, to distinguish between a successful request and a failure:</p><pre>interface Callback&lt;T&gt; {<br>    fun onResponse(data: T)<br>    fun onFailure(t: Throwable)<br>}</pre><p>Then we will create <em>TaskRunner</em>, with an <em>execute</em> method who will receive a <em>callback</em> object, which will be called upon completion of the <em>call</em> method in <em>Task.</em></p><pre>interface TaskRunner&lt;T&gt; {<br>    fun execute(callback: Callback&lt;T&gt;)<br>}</pre><p>The implementation might look like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2448ae54ddcb3e7743173ddeeb4c1128/href">https://medium.com/media/2448ae54ddcb3e7743173ddeeb4c1128/href</a></iframe><p>So we tell the executor to run our <em>Task</em> code, and upon completion we execute our callback’s <em>onResponse</em> on the main thread. If an exception is thrown in the background thread, we will call <em>onFailure</em> on our callback code.</p><p>Our <em>PhotoRepository</em> interface, thus, looks now like this:</p><pre>interface PhotoRepository {<br> fun search(term: String): Task&lt;List&lt;Photo&gt;&gt;<br>}</pre><p>And its implementation now just has to call the service within the <em>call() </em>method of a new <em>Task</em> object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b14f1b25dbd8852d1a2b905a2a36bce/href">https://medium.com/media/6b14f1b25dbd8852d1a2b905a2a36bce/href</a></iframe><p>The <em>ViewModel</em> will now be in charge of holding a <em>TaskRunner</em> who will then execute the job on this <em>Task</em> object, by passing the <em>Callback</em> instance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ed85b0ff88418a9493e6af8fd69aad7/href">https://medium.com/media/2ed85b0ff88418a9493e6af8fd69aad7/href</a></iframe><p>This somehow resembles as well how we did it with RxJava, doesn’t it?</p><p>But wait, how will we make sure we can cancel all of our running tasks if the user closes up the app before they are done executing? What if the user types “Kitten” and then “Kittens” but the first request finishes after the second? We will end up with results from “Kitten” instead of “Kittens” unless we make sure we cancel the previous search before executing the latest one.</p><p>We need to introduce a cancelling mechanism to make sure we still keep the same functionality as before. For that we will use the concept of <a href="https://developer.android.com/reference/java/util/concurrent/Future">Futures</a>.</p><p>If instead of execute we use submit on our executor, we will get an instance of a <em>Future</em>, which we can cancel:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb024387be673cf334787bd99e73d599/href">https://medium.com/media/fb024387be673cf334787bd99e73d599/href</a></iframe><p>And from our <em>MainViewModel</em> we will just make sure we call cancel on the running <em>Task</em> whenever a new search comes in, as well as when the <em>onCleared</em> from our <em>ViewModel</em> is called (upon View destruction):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b7025433347562f523b1cf679b298e4/href">https://medium.com/media/3b7025433347562f523b1cf679b298e4/href</a></iframe><p>And there it is! Upon doing this, we can see the app works and our dependency list looks as empty as this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/866a80e9a8a017070bd104edafab8eaf/href">https://medium.com/media/866a80e9a8a017070bd104edafab8eaf/href</a></iframe><p>So apart from Kotlin’s basic libs, android appCompat and material, and lifecycle &amp; <em>ViewModel</em> extensions, we have removed all libraries!</p><p>This is what the app looks like:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fwm1nKLLJq2I%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dwm1nKLLJq2I&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fwm1nKLLJq2I%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d446b752af9e93c1bb0d4ff101943c9/href">https://medium.com/media/7d446b752af9e93c1bb0d4ff101943c9/href</a></iframe><p>source for this step is found over at <a href="https://github.com/kelmer44/flickr-test/tree/step-4-no-rx">this branch</a></p><h4>Final word</h4><p>Again, the solution I provide is far from a production ready one. It takes many shortcuts and solves the problem mostly in too much of an ad-hoc way. The libraries being replaced have years of hard work by the community on their backs, so replacing them with as good a delivery as they do will take much more time than an interview assignment or a Medium article calls for. This simply illustrates a starting point on how to perform all of these tasks without the help of third party libraries.</p><p>In any case, I am 100% sure some of my implementation could have been done better, cleaner and possibly faster! Please feel free to comment on it on this article.</p><p>Source for the final result is at the master branch over at the repo:</p><p><a href="https://github.com/kelmer44/flickr-test">https://github.com/kelmer44/flickr-test</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ad90428baca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Back to the basics: Android with no libraries (Part 1)]]></title>
            <link>https://medium.com/@kelmer/back-to-the-basics-android-with-no-libraries-part-1-2bd8c5e5d725?source=rss-ce83cb5ab103------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bd8c5e5d725</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Gabriel Sanmartín]]></dc:creator>
            <pubDate>Thu, 14 May 2020 15:16:49 GMT</pubDate>
            <atom:updated>2020-05-14T15:16:49.210Z</atom:updated>
            <content:encoded><![CDATA[<p>Earlier this year I applied for a job at some big tech company whose name I’d rather omit.</p><p>Their process was fairly typical: a live Data Structures/Algorithm code test with one of their engineers, then an assignment, then visit to their HQ, then potential offer.</p><p>After some preparation I got through the live coding test and passed, so they sent me an assignment.</p><p>Now having been on the recruiting side myself for a number of companies in the past, and also with the experience of being the candidate in a few instances, I am somehow used to seeing multiple assignments. Most of the time they involve pretty much the same requirements: consume an API endpoint and present it on the screen, generally under a master/detail flow.</p><p>This case wasn’t the exception: it required the candidate to consume <a href="https://www.flickr.com/services/api/flickr.photos.search.html">flickr’s API for photo search</a> and present the images on the screen with an endless scroll. However, it came with a quirk: the requirements specified that the use of third party libraries wasn’t allowed.</p><blockquote>Flickr’s API for photo search</blockquote><pre>https://api.flickr.com/services/rest?method=flickr.photos.search&amp;format=json&amp;nojsoncallback=1</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4953bb8de9740c69b9355e042655e94/href">https://medium.com/media/a4953bb8de9740c69b9355e042655e94/href</a></iframe><p>While that might sound scary, I decided to devote the following weekend to the task and try and go back into the basics. After all, while we take for granted all those nice libraries that form the tech stack standard on any platform, any good engineer should be able to do it from scratch, right?</p><p>My approach was the following: I would start by quickly producing an app using my library stack of choice, which took me around an hour, then remove each library one by one until I was left with just LiveData and Material Components. My reasoning is that this way at least I would start with something that worked, then do as much as I could without libs and deliver whatever result that I could reach and still worked.</p><p>Also, in this way I could unit test my way into the different steps to make sure everything worked.</p><p>Note that obviously the solution presented here will not be nearly as powerful as any of the libraries it is replacing. It will be taking shortcuts and ad hoc solutions, and thus the code we will produce will in no way be nowhere near production ready. It is, however, a good exercise to cover the basics of an app and understand a little better all the heavy lifting these libraries do for us behind the scenes.</p><p>So let’s go into this first implementation.</p><h4>Step 0: Starting with libraries</h4><p>I went for a pretty standard stack on modern Android development:</p><ul><li>MVVM architecture using LiveData for ViewModel/UI single direction communication</li><li>Glide for background image fetching</li><li>Retrofit for API consumption</li><li>GSON for (de)serializing responses</li><li>RxJava2 for background threading, request transformation and communication between domain layer and ViewModel</li></ul><p>In the end, this is what my <strong>build.gradle</strong> looked like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a55e404a79d5f879d3b422749d023bda/href">https://medium.com/media/a55e404a79d5f879d3b422749d023bda/href</a></iframe><p>I intentionally omitted any Dependency Injection library for simplicity. After all my intention was to replace it anyway and for such small assignment I deemed that to be a bit of overkill. In return, what I did is just set up a <em>ServiceLocator</em> for Singleton dependency definition and Inversion of Control, which was kept through all iterations of the project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12eee25b3068666f6d974107fc1e9bf2/href">https://medium.com/media/12eee25b3068666f6d974107fc1e9bf2/href</a></iframe><p>Other than that, this first approach is pretty straightforward and I will not go too much into detail, since there are a thousand articles on how to build an app with this tech stack.</p><p>You can check the implementation, though, over at <a href="https://github.com/kelmer44/flickr-test/tree/with-rx-glide-retrofit-gson">this branch</a></p><h4>Step 1: Removing Retrofit</h4><p>Let’s start off with the end of the chain, and arguably the easiest: removing the API consumption library.</p><p>With Retrofit, this basically means reimplementing the interface we defined in the previous step:</p><pre>interface FlickrService {<br><br>    fun getSearch(<br>        @Query(&quot;api_key&quot;)<br>        apiKey: String,<br>        @Query(&quot;text&quot;)<br>        term: String<br>    ) : Single&lt;ApiResponse&gt;<br>}</pre><p>Note that Retrofit is a general purpose REST library that supports all HTTP methods, multiple headers and multiple mappers to convert our responses into something with more semantic value. It works by using reflection to implement what we declare in our interface using an <em>HttpClient</em> (that we can specify) and the Adapters we indicate (to transform the format of our responses).</p><p>Obviously we are not gonna reinvent the wheel here, so we will make our implementation a little bit more ad hoc for what we need. That is, we will only implement the minimum to make our <em>getSearch</em> method do what Retrofit was secretly doing for us.</p><p>That means we will create our own <em>HttpClient</em> so that it performs a get request provided with a URL and return a String with the response:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c08614f868cf30e322fb935a552b9ee/href">https://medium.com/media/3c08614f868cf30e322fb935a552b9ee/href</a></iframe><p>We make use of <em>HttpUrlConnection</em> directly to perform a request against our backend, by specifying the URL and the “<em>GET</em>” method directly. Then we just convert our response into a String using a <em>BufferedReader. </em>Pretty stantard Java!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b5eecb487a9bcaa617adb9252706ff2/href">https://medium.com/media/3b5eecb487a9bcaa617adb9252706ff2/href</a></iframe><p>So our Search method can just call this client like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2393082c0cec6889903412cfb478d63/href">https://medium.com/media/d2393082c0cec6889903412cfb478d63/href</a></iframe><p>But wait! We still have RxJava2 as our background processing provider, so we somehow need to convert this into an observable class from Rx. This is easily done by using the fromCallable factory method on the Single object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bab9e7d25f3964eeb3f8e8c1868f822/href">https://medium.com/media/2bab9e7d25f3964eeb3f8e8c1868f822/href</a></iframe><p>And that’s our first step! Pretty straightforward huh? With this, our dependencies section now looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa261135832edb7ee352f11fb5a67ba3/href">https://medium.com/media/fa261135832edb7ee352f11fb5a67ba3/href</a></iframe><p>Check this implementation over at <a href="https://github.com/kelmer44/flickr-test/tree/step1-no-retrofit-no-okhttp">this branch</a></p><h4>Step 2: Removing GSON</h4><p>Now we have removed our REST client to replace it with our own, but we are still relying on our serializer to transform the responses into our value objects.</p><p>Gson also uses reflection to transform the strings responses coming from the backend into objects, by the use of annotations. As we did with Retrofit, we will not be reinventing the wheel but producing an adhoc implementation to cover our scenario.</p><p>In the previous step we abstracted the deserialization by creating an interface like so:</p><pre>interface Serializer {<br><br>    fun deserialize(json: String) : ApiResponse<br>}</pre><p>Which we implemented with GSON by passing in our GSON instance (already in use in our library filled approach):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d323ac5fd7689b1dfadd844a5f0b8a9/href">https://medium.com/media/0d323ac5fd7689b1dfadd844a5f0b8a9/href</a></iframe><p>So to replace GSON we will simply create our own implementation of the Serializer interface.</p><p>The Flickr Api endpoint responses looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4953bb8de9740c69b9355e042655e94/href">https://medium.com/media/a4953bb8de9740c69b9355e042655e94/href</a></iframe><p>Which we modelled like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/359e21fdc0f1d92f5b32160f51390cf2/href">https://medium.com/media/359e21fdc0f1d92f5b32160f51390cf2/href</a></iframe><p>Se we need to make sure we transform our json string into those objects. Working with raw JSON is simple enough, we can just create a <em>JSONObject</em> by passing in our original response string, then iterate through it by getting simple types (<em>Int</em>, <em>String</em>, <em>Double</em>…), other <em>JSONObjects</em>, or <em>JSONArray</em>s:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aab9be9259d2804eb83428afde1fcc3e/href">https://medium.com/media/aab9be9259d2804eb83428afde1fcc3e/href</a></iframe><p>And we are done! Again, in a real world environment we would have to create some flexible solution so every time the json changes we don’t need to change our mapper. Gson (or moshi) does this for us by using reflection to call the getters/setters named after the different fields.*</p><p>*<em>moshi</em> can also generate code for faster runtime (albeit slower compilation time)</p><p>One dependency less makes our <em>build.gradle</em> look like this now:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c61c6cdc9aa1459f81462ab03a7d20f/href">https://medium.com/media/8c61c6cdc9aa1459f81462ab03a7d20f/href</a></iframe><p>I’ve made the source available for this part of the process at <a href="https://github.com/kelmer44/flickr-test/tree/step2-no-gson">this branch</a></p><h4>Next up… Glide and RxJava!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bd8c5e5d725" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>