<?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 Santiago Beroch on Medium]]></title>
        <description><![CDATA[Stories by Santiago Beroch on Medium]]></description>
        <link>https://medium.com/@sberoch?source=rss-df8696b300da------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*M1e2CHW_7YmaPzKQQAPlVA.jpeg</url>
            <title>Stories by Santiago Beroch on Medium</title>
            <link>https://medium.com/@sberoch?source=rss-df8696b300da------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 18:07:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sberoch/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[Android Architecture: Hilt, MVVM, Kotlin Coroutines, Live Data, Room and Retrofit (ft.]]></title>
            <link>https://itnext.io/android-architecture-hilt-mvvm-kotlin-coroutines-live-data-room-and-retrofit-ft-8b746cab4a06?source=rss-df8696b300da------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b746cab4a06</guid>
            <category><![CDATA[android-architecture]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Santiago Beroch]]></dc:creator>
            <pubDate>Tue, 14 Jul 2020 02:04:20 GMT</pubDate>
            <atom:updated>2020-07-17T13:47:20.789Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android Architecture: Hilt, MVVM, Kotlin Coroutines, Live Data, Room and Retrofit (ft. Rick and Morty)</h3><p>When developing an Android app it is important to plan the architecture of the project. This will allow us to create complex, robust, good quality, easy to maintain applications.</p><p>Today I want to show you my approach to using the recommended practices in Android development.</p><p>As you know, writing all of our app code in an Activity or Fragment is a common mistake. We should separate the different concerns of our app components. This next diagram will show you the modules and their interactions that we will be using:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*3u5JnmqONR4UnwRE6tEV3Q.png" /><figcaption>Android Architecture Components</figcaption></figure><h3>The project</h3><p>We will be using <a href="https://rickandmortyapi.com/">the Rick and Morty API,</a> from where we will extract character information to show them in a RecyclerView, and by clicking one of its items the app will display the detail of one character. Simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*GFYCU0E0AdvRvrSW2mBHzw.jpeg" /><figcaption>The app</figcaption></figure><p>And this is the project’s folder structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*hA5dx2m07_sGfuh1vSu3Cw.png" /><figcaption>Folder Structure</figcaption></figure><p>That could seem like a lot. Here is some explanation:</p><p><strong>data: </strong>Our M (Model) in MVVM. Where we perform data operations.</p><p><strong>di: </strong>Dependency Injection with the help of Hilt.</p><p><strong>ui</strong>: Our Fragments and ViewModels helping to display data to the user.</p><p><strong>utils</strong>: Helper classes and functions.</p><p>I recommend that you have a look at the GitHub repository while you follow this tutorial.</p><p><a href="https://github.com/sberoch/RickAndMorty-AndroidArchitectureSample">sberoch/RickAndMorty-AndroidArchitectureSample</a></p><p>One last thing before continuing. The API returns this response when asking for a list of characters</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11967a2b5558989331d1969daa6ac313/href">https://medium.com/media/11967a2b5558989331d1969daa6ac313/href</a></iframe><p>We are getting a paginated response. The actual characters are returned under “results”. That’s why you will find three classes under the folder <em>entities. </em>But the most important one is Character.</p><p>Having said that, we move on to Hilt and DI.</p><h3>Hilt</h3><p>This is not a DI tutorial so I strongly advise to get a little more familiar with the concept before continuing. I’ll briefly explain it anyway.</p><p>It is very common for applications where concerns are separated that some of the components have dependencies. The <strong>ViewModel </strong>depends on the <strong>Repository </strong>to get the data. But the Repository depends on a <strong>CharacterRemoteDataSource</strong> and a <strong>CharacterDao</strong> as well. And this is a simple app. It could turn into a dependency hell pretty fast.</p><p>Hilt comes to the rescue. We just need to inform where do we need to inject those dependencies and where should it get them from.</p><p>We start by creating in the root folder a class that inherits from Application, to annotate it, informing that we will use Hilt in the app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29372a7acfaefe339a8930e06348f17b/href">https://medium.com/media/29372a7acfaefe339a8930e06348f17b/href</a></iframe><p>Then, we need to annotate each Activity and Fragment as AndroidEntryPoints:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29f0e56da7ff8ab4ae0a0827772967f2/href">https://medium.com/media/29f0e56da7ff8ab4ae0a0827772967f2/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78e9b32ed41aa2dcd43afe7b331fe65f/href">https://medium.com/media/78e9b32ed41aa2dcd43afe7b331fe65f/href</a></iframe><p>Our next step is to now create our<strong> </strong>Module inside the di folder. If you are not so familiar with di concepts, think of the module as the “bag” from where we will get our dependencies from. (I’ll show many dependencies from upcoming sections of this tutorial, so don’t be scared if you don’t understand all of them now).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/156227e36be38d7d67b702bf27f7613d/href">https://medium.com/media/156227e36be38d7d67b702bf27f7613d/href</a></iframe><p><strong>@Module </strong>annotates the object to indicate that we will get our dependencies from here. We’ll only use one in this simple app, but larger scale projects usually have many modules.</p><p><strong>@Singleton </strong>will force that only one instance of the dependency will be created and used across the entire app.</p><p><strong>@Provides </strong>indicates that the upcoming function will provide a dependency.</p><p>So how do I do the injection?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6ff2fa016a6c3631a485ed4c8097690/href">https://medium.com/media/c6ff2fa016a6c3631a485ed4c8097690/href</a></iframe><h3>ViewModel, LiveData, and data display.</h3><p>Thanks to the usage of LiveData and Kotlin Coroutines we can avoid callbacks and have a really simple way to present our data to our views. This is how this ViewModel does it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f7e92aadcf6cfff0f53111ffa68bfba/href">https://medium.com/media/4f7e92aadcf6cfff0f53111ffa68bfba/href</a></iframe><p>You may be wondering about <strong>Resource. </strong>It is this helper class</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bfecbf9a068614acb9ff441e41bf07d/href">https://medium.com/media/9bfecbf9a068614acb9ff441e41bf07d/href</a></iframe><p>It helps us encapsulate our repository responses according to their state, making it easy for our views to display information accordingly. This is how CharactersFragment observes a LiveData value and updates itself accordingly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33fe2a1976b3068ad175bc474bc49eb7/href">https://medium.com/media/33fe2a1976b3068ad175bc474bc49eb7/href</a></iframe><p>We have our presentation layer. How do I get my data?</p><h3>Retrofit and remote data.</h3><p>Retrofit helps us access remote data from our app. You can see how to build a Retrofit object in <strong>AppModule.kt</strong>. We also need to code interfaces with the HTTP operations that we will perform to communicate with the API.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec9ff733e6848d60f0db4e3190d523f3/href">https://medium.com/media/ec9ff733e6848d60f0db4e3190d523f3/href</a></iframe><p>The <strong>suspend</strong> modifier is brought to us by Kotlin Coroutines, it indicates that the following function will execute in a coroutine (similar to a thread) allowing us to keep the UI thread unblocked while long lasting operations such as getting our data from the internet are being executed.</p><p>This CharacterService is used by CharacterRemoteDataSource</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/071f1f8a96e6ddca16717c372009725c/href">https://medium.com/media/071f1f8a96e6ddca16717c372009725c/href</a></iframe><p>Why do we do this? Fair question. <strong>getResult </strong>encapsulates the Retrofit response in a <strong>Resource</strong>, so that we can catch errors nicely.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ee75b0254a98fba05a20bfcf87e237a/href">https://medium.com/media/4ee75b0254a98fba05a20bfcf87e237a/href</a></iframe><h3>Room and local data storage</h3><p>On the other hand, we are also interested in storing and getting data from a local database. We need it in order to show at least something to our users when they are out of connection. If you are familiar with the concept, we are going to use it as a <em>cache</em> for our system.</p><p>Room brings us a nice interface to work with local databases. Here’s we build one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e5e47cbe28d070d3bec51b937278388/href">https://medium.com/media/5e5e47cbe28d070d3bec51b937278388/href</a></iframe><p>Don’t forget to include all the entities you want to persist in the <strong>@Database </strong>annotation. In order for Room to see our entities, we will need to also annotate them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ac4d4d61c57f886b604bafef76530d7/href">https://medium.com/media/4ac4d4d61c57f886b604bafef76530d7/href</a></iframe><p>Lastly, we need to specify the operation that we will be performing on the database. That’s where our DAOs kick in (Data Access Object)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47af5ce5b62231fbacae03c61e1b9c96/href">https://medium.com/media/47af5ce5b62231fbacae03c61e1b9c96/href</a></iframe><p>Note that Room has LiveData support, so you can get observable values from the database. And Kotlin Coroutines makes it even easier by letting us suspend our Room functions.</p><h3>Repository and our caching strategy</h3><p>Let’s join both of our data sources. This is the time where we need to plan a data access strategy. Think, for example, in the process of getting a Character.</p><ul><li>First we need to let our LiveData know that we are looking for the Character, so that it should have a LOADING state.</li><li>Then, we would like to get that character from the local data source, because it is faster than getting it from the internet. If it finds it, we are changing the state to a SUCCESS</li><li>Regardless of the result of the local database operation, we would want to keep our app synced, so we are fetching that character from the internet as well (but remember that the ui thread won’t be blocked and the user could already be shown the correct character information because of it being in the database!).</li><li>Finally, we need to save our result from the remote call in the database, in order to keep it updated.</li></ul><p>We will be doing all of this in our Repository:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6bee11c3b82f78a8204adb44f29100b/href">https://medium.com/media/c6bee11c3b82f78a8204adb44f29100b/href</a></iframe><p>The <strong>performGetOperation </strong>is defined following the strategy we discussed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d7018ddca791a9d5c16d3236885ddbd/href">https://medium.com/media/1d7018ddca791a9d5c16d3236885ddbd/href</a></iframe><p>I want to highlight the first line where we do <strong>liveData(Dispatchers.IO)</strong></p><p>Thanks to Kotlin Coroutines and LiveData, when we do that we are launching a new IO coroutine, therefore letting us use our suspend funcions, and we are as well storing our results in a LiveData holder, which is being observed by the ViewModel.</p><p>And that’s it!</p><h3>Further Steps</h3><p>We made it to the end. I hope I was clear throughout the tutorial.</p><p>We have some TODOs that I omitted in order to keep things short:</p><ul><li>We are syncing all the time with the strategy I presented, and your application might not need it. Keep your needs in mind and develop a smart strategy.</li><li>Also, we are only performing get operations. What if we need to upload something to a server? The strategy will also be different in such case.</li><li>The API paginates its characters. Why don’t we? Take a look at Paging Library by Jetpack.</li><li>Testing is yet to be made.</li></ul><p>That’s all. Remember you can find all the code I used in the GitHub repository</p><p><a href="https://github.com/sberoch/RickAndMorty-AndroidArchitectureSample">sberoch/RickAndMorty-AndroidArchitectureSample</a></p><p>And if any of this was useful to you, leave a <strong>Clap</strong>! I would be very grateful and motivated for a next tutorial.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b746cab4a06" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/android-architecture-hilt-mvvm-kotlin-coroutines-live-data-room-and-retrofit-ft-8b746cab4a06">Android Architecture: Hilt, MVVM, Kotlin Coroutines, Live Data, Room and Retrofit (ft.</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arquitectura en Android: Hilt, MVVM, Kotlin Coroutines, Live Data, Room y Retrofit]]></title>
            <link>https://sberoch.medium.com/arquitectura-en-android-hilt-mvvm-kotlin-coroutines-live-data-room-y-retrofit-68bf458ec76e?source=rss-df8696b300da------2</link>
            <guid isPermaLink="false">https://medium.com/p/68bf458ec76e</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[desarrollo-de-software]]></category>
            <category><![CDATA[arquitectura-de-software]]></category>
            <dc:creator><![CDATA[Santiago Beroch]]></dc:creator>
            <pubDate>Mon, 13 Jul 2020 14:56:25 GMT</pubDate>
            <atom:updated>2020-07-13T14:56:25.922Z</atom:updated>
            <content:encoded><![CDATA[<p>A la hora de desarrollar para la plataforma Android es importante pensar en la arquitectura que va a tener el proyecto. Esto permitirá que realicemos aplicaciones complejas, robustas, fáciles de mantener, y de buena calidad.</p><p>Hoy quiero presentar un enfoque para usar las mejores practicas en el desarrollo Android.</p><p>Como sabrán, escribir toooodo el código en una Activity o un Fragment es un error común. Es importante separar las incumbencias de cada porción del código. El siguiente diagrama muestra los módulos y sus interacciones de la aplicación que vamos a crear:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*-yY0l4XD3kLcZz0rO1sfRA.png" /><figcaption>Componentes de arquitectura Android</figcaption></figure><p>Es probable que no sepas que son algunas de las cosas que están en el diagrama. No te preocupes, los vamos a ver a lo largo del tutorial. Mientras tanto, acá muestro brevemente de que se trata cada cosa:</p><ul><li><strong>Retrofit: </strong>Librería que nos permite fácilmente obtener datos de una API en la web.</li><li><strong>Room: </strong>Nos ayuda a guardar los datos de nuestra aplicación en una base de datos local. Es de utilidad para crear copias locales de los datos que obtenemos de Internet, generando una mejor experiencia.</li><li><strong>Repository: </strong>Este patrón de diseño es útil para combinar los puntos anteriores y crear una buena estrategia de acceso a los datos, mientras que para el resto de la aplicación sea muy sencillo.</li><li><strong>ViewModel: </strong>Se encarga de acceder a los datos y realizar las transformaciones necesarias para mostrarlas en la vista.</li><li><strong>LiveData: </strong>Es una variable donde se guardan datos observables. Otro componente los observara y actuara en consecuencia. Esto permite ahorrarnos el uso de callbacks como se usan en otros patrones de arquitectura como MVP, que suelen hacer al código un poco mas difícil de leer.</li><li><strong>Hilt: </strong>Para realizar Dependency Injection, o Inyección de Dependencias. Basado en el popular Dagger.</li></ul><h3>El proyecto</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49PVJod6M7Cm5G94cO0-iw.jpeg" /><figcaption>Capturas de la app</figcaption></figure><p>Estaremos usando la <a href="https://rickandmortyapi.com/">API de Rick and Morty</a>, de donde obtendremos información de los personajes para mostrarlos en un Recycler View, y luego se podrá hacer click en cada uno para obtener el detalle de cada personaje. Super simple.</p><p>Esta es una imagen de como esta estructurado el proyecto en carpetas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*embETqqtaGUGEsjmXKcGbA.png" /><figcaption>Estructura del proyecto</figcaption></figure><p>Puede llegar a parecer mucho, pero todo esta ahí por una razón.</p><p><strong>data: </strong>Acá encontramos todo lo que se refiere al acceso a los datos y como los vamos a modelar.</p><p><strong>di: </strong>Inyección de dependencias. Lo explico en la siguiente sección.</p><p><strong>ui</strong>: La parte visual de la aplicación. Incluye los fragmentos y los viewmodel.</p><p><strong>utils</strong>: Clases y funciones que darán asistencia a otros componentes del proyecto.</p><p>Recomiendo que vayas viendo el repositorio en GitHub por si quedo alguna duda de que hay en cada lugar:</p><p><a href="https://github.com/sberoch/RickAndMorty-AndroidArchitectureSample">sberoch/RickAndMorty-AndroidArchitectureSample</a></p><p>Una cosa a tener en cuenta. La API devuelve una respuesta con este formato cuando se le pide una lista de personajes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11967a2b5558989331d1969daa6ac313/href">https://medium.com/media/11967a2b5558989331d1969daa6ac313/href</a></iframe><p>Es decir esta paginada. “info” muestra la pagina actual y en “results” se encuentran los personajes en si. Es por eso que existen 3 clases en la carpeta data/entities, pero no es necesario prestarle atención a todas, la importante es <strong>Character.</strong></p><p>Dicho esto, seguimos con Hilt y Inyección de Dependencias.</p><h3>Hilt</h3><p>Este no es un tutorial de Inyección de Dependencias, por lo que si este tema te cuesta recomiendo primero buscar un tutorial sobre ello y volver. Aun así lo explicare brevemente.</p><p>Es muy común que en las aplicaciones donde se separan los componentes haya dependencias. El <strong>viewmodel </strong>depende del <strong>repository </strong>para conseguir sus datos, pero a su vez el <strong>repository</strong> depende del <strong>characterRemoteDataSource </strong>y del <strong>characterDao </strong>para conseguir esto mismo. Y así sucesivamente. Rápidamente esto se convierte en un problema ya que los constructores de los componentes quedan muy cargados.</p><p>Hilt nos va a ayudar con esto. Solo hay que informarle a donde inyectar estas dependencias y de donde sacarlas, ademas de algunas cosas especiales en las clases de Android que no se construyen tan simplemente.</p><p>Empezamos por crear en la carpeta base una clase que herede de Application. Informaremos aquí que usaremos Hilt.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29372a7acfaefe339a8930e06348f17b/href">https://medium.com/media/29372a7acfaefe339a8930e06348f17b/href</a></iframe><p>Luego hay que anotar cada Activity y Fragment donde se inyecten dependencias de la siguiente manera.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29f0e56da7ff8ab4ae0a0827772967f2/href">https://medium.com/media/29f0e56da7ff8ab4ae0a0827772967f2/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78e9b32ed41aa2dcd43afe7b331fe65f/href">https://medium.com/media/78e9b32ed41aa2dcd43afe7b331fe65f/href</a></iframe><p>Hecho esto, creemos dentro de la carpeta di el archivo <strong>AppModule </strong>, la “bolsa” donde estarán todas las dependencias que proveeremos a los componentes. (Hay muchas dependencias de partes posteriores del tutorial, no te asustes si no se entiende muy bien que es lo que se esta creando).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/156227e36be38d7d67b702bf27f7613d/href">https://medium.com/media/156227e36be38d7d67b702bf27f7613d/href</a></iframe><p><strong>@Module </strong>indica que en el objeto anotado se proveerán dependencias. En este tutorial se usa uno solo pero en aplicaciones mas grandes deberían usar varios, separados por incumbencias.</p><p><strong>@Singleton </strong>indicara que solo se puede crear un objeto de la clase a inyectar, y usarse este mismo todas las veces que lo necesiten.</p><p><strong>@Provides </strong>indica que se esta creando una dependencia a inyectar en la función anotada.</p><p>Ahora solo resta hacer la propia inyección de las dependencias:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6ff2fa016a6c3631a485ed4c8097690/href">https://medium.com/media/c6ff2fa016a6c3631a485ed4c8097690/href</a></iframe><p>Mediante la anotación <strong>@Inject </strong>se le indica a Hilt que necesita las dependencias del constructor, e ira a buscarlas a <strong>AppModule.</strong></p><h3>ViewModel, LiveData, y la presentación de los datos</h3><p>Estamos usando MVVM (Model-View-ViewModel) para este proyecto. Vamos por el ViewModel, que nos queda super sencillo gracias al uso de LiveData.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f7e92aadcf6cfff0f53111ffa68bfba/href">https://medium.com/media/4f7e92aadcf6cfff0f53111ffa68bfba/href</a></iframe><p>Simplemente es pedirle los personajes al repositorio y guardarlos en un LiveData.</p><p>Te preguntaras por Resource. Es esta clase de asistencia:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bfecbf9a068614acb9ff441e41bf07d/href">https://medium.com/media/9bfecbf9a068614acb9ff441e41bf07d/href</a></iframe><p>No es algo tan usual de ver, pero es bastante simple. Permite encapsular las respuestas de nuestro repositorio según su estados (mientras esta cargando, cuando se cargo con éxito, y cuando ocurrió algún error).</p><p>Finalmente, la vista debe observar el LiveData para responder ante los cambios de dichos estados. Así es como:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33fe2a1976b3068ad175bc474bc49eb7/href">https://medium.com/media/33fe2a1976b3068ad175bc474bc49eb7/href</a></iframe><h3>Retrofit y obtener datos remotamente</h3><p>Tenemos la capa de presentación ¿Como accedo a los datos?</p><p>Retrofit nos ayuda a enviar y recibir datos de la API. Su construcción la vemos en <strong>AppModule </strong>. Al usar Retrofit hay que crear interfaces con las operaciones HTTP que vamos a realizar para comunicarse con el exterior.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec9ff733e6848d60f0db4e3190d523f3/href">https://medium.com/media/ec9ff733e6848d60f0db4e3190d523f3/href</a></iframe><p>Te aconsejo ver un tutorial de Retrofit si no se entiende todo. Solo quiero detenerme en el modificador <strong>suspend </strong>que nos brinda Kotlin Coroutines. Indica que la función se ejecutara dentro de una Corutina (Podes verlo como un thread, o un hilo de ejecución).</p><p>Sirve mucho ya que no queremos que nuestro hilo de ejecución principal (Lo que ve el usuario, la UI) se detenga mientras esperamos que se descarguen todos los personajes.</p><p>El <strong>CharacterService </strong>que usa retrofit se encuentra encapsulado por <strong>CharacterRemoteDataSource .</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/071f1f8a96e6ddca16717c372009725c/href">https://medium.com/media/071f1f8a96e6ddca16717c372009725c/href</a></iframe><p>Es bien simple, se encarga de guardar el resultado en uno de esos Resources que les mostré antes, ahora lo vemos en la función <strong>getResult.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ee75b0254a98fba05a20bfcf87e237a/href">https://medium.com/media/4ee75b0254a98fba05a20bfcf87e237a/href</a></iframe><h3>Room y el acceso a datos localmente</h3><p>Por otra parte, también nos interesa guardar y acceder datos localmente. Nos puede interesar mostrarle algo al usuario cuando no tiene conexión a internet. Tambien sirve como una cache, donde en lugar de ir a buscar datos a internet los obtengo del almacenamiento local, mucho mas rápido.</p><p>Room se encargara de esto. Primero debemos definir la Base de Datos.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e5e47cbe28d070d3bec51b937278388/href">https://medium.com/media/5e5e47cbe28d070d3bec51b937278388/href</a></iframe><p>Lo mas importante del código de arriba es escribir en la anotación <strong>@Database </strong>todas las entidades que van a ser guardadas en la base de datos, en nuestro caso solo Character, que como veremos, hay que anotarla para que la pueda reconocer Room.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ac4d4d61c57f886b604bafef76530d7/href">https://medium.com/media/4ac4d4d61c57f886b604bafef76530d7/href</a></iframe><p>Al trabajar con Room también hay que indicarle las operaciones que se van a realizar sobre esa base de datos. Eso se hace con los DAO (Data access object).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47af5ce5b62231fbacae03c61e1b9c96/href">https://medium.com/media/47af5ce5b62231fbacae03c61e1b9c96/href</a></iframe><p>Si tenes conocimientos de SQL, se trata de anotar funciones con la operación SQL que realizamos en cada momento. Hay que notar que Room tiene soporte para LiveData, por lo que puedo obtener mis datos en un observable de ese tipo, y para Kotlin Coroutines, por lo que puedo usar el modificador <strong>suspend .</strong></p><h3>Repository: Organizando la estrategia para acceder a los datos</h3><p>Juntemos ambas formas de acceder a los datos. Es ahora el momento donde hay que idear una estrategia de cacheo. Pensemos en la operación de obtener un personaje.</p><ul><li>Primero hay que avisarle al LiveData que estamos buscando el dato, por lo que se asignara un estado LOADING.</li><li>Luego es deseable tratar de obtenerlo desde la base de datos local, ya que esto es mucho mas rápido. Si lo encuentra cambiara el estado del LiveData a SUCCESS.</li><li>A su vez, se lo descargara desde internet donde esta la información actualizada. Es probable que si se actualizo esta información se actualice el LiveData nuevamente.</li><li>Por ultimo debemos guardar esta información obtenida desde internet en la base de datos, a fin de actualizarla (o probablemente guardarla, si no se encontraba ahí en primer lugar).</li></ul><p>Todo esto estaremos haciendo en el repository</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6bee11c3b82f78a8204adb44f29100b/href">https://medium.com/media/c6bee11c3b82f78a8204adb44f29100b/href</a></iframe><p>La función <strong>performGetOperation </strong>se definió así, de acuerdo a la estrategia que planeamos.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d7018ddca791a9d5c16d3236885ddbd/href">https://medium.com/media/1d7018ddca791a9d5c16d3236885ddbd/href</a></iframe><p>Suena complicada, pero hace lo que hablamos antes. Solo quiero destacar el principio del bloque donde hacemos <strong>liveData(Dispatchers.IO) </strong>.</p><p>Mediante el soporte de Kotlin Coroutines con LiveData, al usar eso estamos ejecutando una nueva corutina que va a realizar operaciones IO (Entrada/salida), y por lo tanto se nos permite ejecutar las funciones <strong>suspend </strong>que vimos previamente, y guardando los resultados que vamos generando en un LiveData, que observara el ViewModel, para que a su vez lo observe la Vista. Todo cierra.</p><h3>Próximos Pasos</h3><p>Llegamos al final. Espero haber sido claro.</p><p>Algunas cosas quedan pendientes pero no quería extenderme demasiado. Así que pensemos algunos próximos pasos.</p><ul><li>Esta estrategia de acceso a datos que implementamos busca datos en internet todo el tiempo para sincronizar. Pero en tu caso puede no ser necesario y puede ser deseable acceder con menos frecuencia a la fuente de datos remota.</li><li>Ademas, la única operación que implementamos es la de obtener datos ¿Que pasa si los quiero enviar? No me interesa guardar en LiveData lo que envio porque ya lo tengo. Ademas, depende de cada caso puede ser deseable o no guardar lo que envio en la base de datos.</li><li>La API que estamos usando nos permite paginar los resultados. Estaría bueno usarlo. Ver Paging Library de Jetpack.</li><li>Testing</li></ul><p>Eso es todo. Recorda que podes encontrar todo el código en el repositorio en GitHub:</p><p><a href="https://github.com/sberoch/RickAndMorty-AndroidArchitectureSample">sberoch/RickAndMorty-AndroidArchitectureSample</a></p><p>Si este tutorial te resulto de utilidad, un <strong>clap </strong>sera apreciado e inspirador para próximos tutoriales.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68bf458ec76e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>