<?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 Jorge Sánchez (xurxodev) on Medium]]></title>
        <description><![CDATA[Stories by Jorge Sánchez (xurxodev) on Medium]]></description>
        <link>https://medium.com/@xurxodev?source=rss-c3fe54d1497b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SyI24wlN6ecXt1kR8a8Unw.jpeg</url>
            <title>Stories by Jorge Sánchez (xurxodev) on Medium</title>
            <link>https://medium.com/@xurxodev?source=rss-c3fe54d1497b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 07:47:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@xurxodev/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[Moving Away from React and Vue.js]]></title>
            <link>https://javascript.plainenglish.io/frontend-clean-architecture-ca2592bd9d58?source=rss-c3fe54d1497b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca2592bd9d58</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jorge Sánchez (xurxodev)]]></dc:creator>
            <pubDate>Sun, 11 Jul 2021 19:45:33 GMT</pubDate>
            <atom:updated>2023-07-11T15:14:35.272Z</atom:updated>
            <content:encoded><![CDATA[<h4>Moving Away from React and Vue.js on the Front-End using Clean Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5xM7RDJ7wQruOA5FzDGRw.png" /><figcaption>front-end Clean Architecture</figcaption></figure><p>This article is an English translation of the original in my blog: <a href="http://xurxodev.com/frontend-clean_architecture/">Alejándonos de ReactJs y VueJs en el front end usando Clean Architecture</a>.</p><p>Subscribe to my Spanish newsletter where I write stories about my vision of the software development: <a href="https://xurxodev.com/#/portal/signup">https://xurxodev.com/#/portal/signup</a></p><p>One of the advantages of using Clean Architecture, among others, is the ability to uncouple our application of the delivery mechanism to the user, that is, from the UI framework or library.</p><p>This advantage in long-term applications allows us to adapt in the future to the changes that will surely take place in libraries and frameworks.</p><p>In this article, we will take Clean Architecture to the extreme in the front-end by applying two delivery mechanisms: React and Vue.js.</p><p>We will have as much code as possible reused between the two implementations.</p><p>This will be possible by creating the domain, data, and remote display logic of React and Vue.js.</p><h3>Why move away from the framework?</h3><p>I have developed different technologies applying Clean Architecture like .Net, Android, iOS, and Flutter. For a long time, I am also programming in the front-end and writing about it.</p><p>One of the biggest problems when it comes to evolving an application is the coupling to the UI framework.</p><p>On the front-end little by little due to the responsibilities that applications of this type have been gained over time, it makes more and more sense to develop in a more structured way and the problems to be solved are very similar to those that exist on other fronts such as backend or mobile development.</p><p>There are frameworks like React and Vue.js that make life easier for us to take on these challenges on the front-end.</p><p>A front-end application today is an independent application of the backend in many cases and therefore needs to have its own architecture.</p><p>In addition, this architecture must help us in the next points:</p><ul><li>Independent of UI, frameworks, API rest and persistence, databases o third-party services.</li><li>Escalability.</li><li>Testability.</li></ul><p>This means that if we change the vision of having a ReactJs or VueJs application, to have a front-end application that uses ReactJs or VueJs to render, this will make our lives much easier in the future.</p><p>So, for example, evolving your ReactJS application from using classes as before, to using functions and hooks as is done now, is much more trivial. The same happens if you switch in VueJS from using the options API to the composition API.</p><p>It’s more trivial because you only use the framework for what is strictly necessary, such as rendering and thus you do not overuse it, keeping it away from any type of logic, be its domain, data, or presentation logic.</p><blockquote>Frameworks evolve and you cannot control that, but what you can control is the coupling you have with them and how their changes affect you.</blockquote><p>But in this case, we are going to go beyond how to adapt to changes that can happen in a framework and we are going to see the amount of code that could not change when we modify ReactJS by VueJS if we use Clean Architecture and separate responsibilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iPChCgSKp1XldkNCOUxk6Q.png" /><figcaption>Clean architecture</figcaption></figure><p>This is the picture you keep in mind if you develop using <strong>Clean Architecture</strong>.</p><p>If you don’t have clear the concepts of Clean Architecture, I recommend that you read this <a href="http://xurxodev.com/por-que-utilizo-clean-architecture-en-mis-proyectos/">article</a>.</p><p>The most important part is the dependency rule, so if you don’t know what I’m talking about, I recommend that you read this <a href="http://xurxodev.com/por-que-utilizo-clean-architecture-en-mis-proyectos/">article</a>.</p><p>The example that we are going to see is based on the one we saw in this <a href="http://xurxodev.com/el-patron-bloc-junto-a-clean-architecture-en-reactjs/">article</a>.</p><h3>Our scenario</h3><p>It’s a shopping cart with enough functionality to look like a real example. We are going to have a global state, non-global state, and we will simulate invoke to a remote service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k8E5StCvDtctSV3MQ0GtIg.png" /><figcaption>Shopping Cart Example</figcaption></figure><h3>Architecture</h3><p>At the project structure level, we will use a monorepo using <a href="https://classic.yarnpkg.com/en/docs/workspaces/">yarn workspaces</a>, in this way we can split the project into modules or packages sharing code between them.</p><p>We have several packages:</p><ul><li>Core: in this package, we will have all the shared code between the app rendered by ReactJS and the app rendered by VueJs.</li><li>React: in this package is found the react app version.</li><li>Vue: in this package is found the Vue app version.</li></ul><h3>¿What code is reused?</h3><p>We are going to reuse all the code that we must have uncoupled from the UI Framework, since being different versions of the same app it makes sense that this code is shared and not write twice.</p><p>This is a demonstration exercise of the potential that Clean Architecture has but this uncoupling of the UI framework is necessary even when we develop a real app.</p><p>Using the UI framework for what is strictly necessary allows us to better adapt to changes in future versions of the framework.</p><p>This is because the code that contains the application logic, which is the most important part, that changes less over time, and is the code potentially to be shared between two versions of the same app as in this example, it’s uncoupled without depending on the UI framework.</p><p>In Clean Architecture the domain layer is where the enterprise and application business logic is located.</p><p>The data layer is where we communicate with the persistence.</p><p>The presentation logic is the one that decides what data is shown if something should be visible or not if it should be shown to the user that we are loading data or if an error should be displayed. It is where the state of the components is managed.</p><p>Each of these 3 parts contains logic that we must uncouple and is found in the core package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*857ZuG0GUgZHyZyghwdKFg.png" /><figcaption>Front-end Clean architecture packages</figcaption></figure><h3>Domain Layer</h3><p>The domain layer is where the enterprise and application business logic is located.</p><h4>Use Cases</h4><p>Use cases are intents, contains the business logic of the application, they are actions and in this example, we have the next:</p><ul><li>GetProductsUseCase</li><li>GetCartUseCase</li><li>AddProductToCartUseCase</li><li>EditQuantityOfCartItemUseCase</li><li>RemoveItemFromCartUseCase</li></ul><p>Let’s see the example of GetProductsUseCase:</p><pre>export class GetProductsUseCase {<br>    private productRepository: ProductRepository;</pre><pre>constructor(productRepository: ProductRepository) {<br>        this.productRepository = productRepository;<br>    }</pre><pre>execute(filter: string): Promise&lt;Either&lt;DataError, Product[]&gt;&gt; {<br>        return this.productRepository.get(filter);<br>    }<br>}</pre><p>This use case is simple because it consists of a simple call to the data layer, in other contexts where, for example, when creating a product, we have to validate that there is no longer one with the same SKU, there would be more logic.</p><p>The use cases returns Either type, if you are not sure what it is then I recommend that you read this <a href="http://xurxodev.com/either-en-typescript/">article</a> and this <a href="http://xurxodev.com/either-asincrono-con-promesas-en-typescript/">article</a>.</p><p>In this way, the error handling is not done using the catch of the promises, but the result object of the promise itself tells you if the result is successful or not.</p><p>The use of Either versus the classic try-catch has several advantages:</p><ul><li>The flow of execution is simpler to follow without jumps between callers when an error occurs.</li><li>That something can go wrong, is explicitly indicated.</li><li>Errors that may occur are explicitly indicated.</li><li>Doing the use of the <a href="http://xurxodev.com/either-en-typescript">exhaustive switch</a>, if you add more errors in the future, TypeScript will warn you where you have not taken this new error into account.</li></ul><p>The type for the errors is as follows:</p><pre>export interface UnexpectedError {<br>    kind: &quot;UnexpectedError&quot;;<br>    message: Error;<br>}</pre><pre>export type DataError = UnexpectedError;</pre><p>Potentially in the future, it could evolve to something like this:</p><pre>export interface ApiError {<br>    kind: &quot;ApiError&quot;;<br>    error: string;<br>    statusCode: number;<br>    message: string;<br>}</pre><pre>export interface UnexpectedError {<br>    kind: &quot;UnexpectedError&quot;;<br>    message: Error;<br>}</pre><pre>export interface Unauthorized {<br>    kind: &quot;Unauthorized&quot;;<br>}</pre><pre>export interface NotFound {<br>    kind: &quot;NotFound&quot;;<br>}</pre><pre>export type DataError = ApiError | UnexpectedError | Unauthorized;</pre><p>And in the presentation layer, if I’m using an exhaustive switch, Typescript would warn me, I should add more cases for each new error.</p><h4>Entities</h4><p>The entities contain the enterprise business logic.</p><p>Let’s see the example of Cart:</p><pre>type TotalPrice = number;<br>type TotalItems = number;</pre><pre>export class Cart {<br>    items: readonly CartItem[];<br>    readonly totalPrice: TotalPrice;<br>    readonly totalItems: TotalItems;</pre><pre>constructor(items: CartItem[]) {<br>        this.items = items;<br>        this.totalPrice = this.calculateTotalPrice(items);<br>        this.totalItems = this.calculateTotalItems(items);<br>    }</pre><pre>static createEmpty(): Cart {<br>        return new Cart([]);<br>    }</pre><pre>addItem(item: CartItem): Cart {<br>        const existedItem = this.items.find(i =&gt; i.id === item.id);</pre><pre>if (existedItem) {<br>            const newItems = this.items.map(oldItem =&gt; {<br>                if (oldItem.id === item.id) {<br>                    return { ...oldItem, quantity: oldItem.quantity + item.quantity };<br>                } else {<br>                    return oldItem;<br>                }<br>            });</pre><pre>return new Cart(newItems);<br>        } else {<br>            const newItems = [...this.items, item];</pre><pre>return new Cart(newItems);<br>        }<br>    }</pre><pre>removeItem(itemId: string): Cart {<br>        const newItems = this.items.filter(i =&gt; i.id !== itemId);</pre><pre>return new Cart(newItems);<br>    }</pre><pre>editItem(itemId: string, quantity: number): Cart {<br>        const newItems = this.items.map(oldItem =&gt; {<br>            if (oldItem.id === itemId) {<br>                return { ...oldItem, quantity: quantity };<br>            } else {<br>                return oldItem;<br>            }<br>        });</pre><pre>return new Cart(newItems);<br>    }</pre><pre>private calculateTotalPrice(items: CartItem[]): TotalPrice {<br>        return +items<br>            .reduce((accumulator, item) =&gt; accumulator + item.quantity * item.price, 0)<br>            .toFixed(2);<br>    }</pre><pre>private calculateTotalItems(items: CartItem[]): TotalItems {<br>        return +items.reduce((accumulator, item) =&gt; accumulator + item.quantity, 0);<br>    }<br>}</pre><p>In this example, the entities are simple, with properties of primitive types, but a real example where there were validations we could have Entities and V<a href="http://xurxodev.com/como-crear-value-object-en-typescript/">alue Objects</a> defined as classes and with factory methods where the validation is performed. We use Either to return the errors or the result.</p><h4>Boundaries</h4><p>The boundaries are the abstractions of the adapters, for example, in Hexagonal Architecture they are called ports. They are defined in the layer of the use cases in the domain and indicate how we are going to communicate with the adapters</p><p>For example, to communicate with the data layer we use the repository pattern.</p><pre>export interface ProductRepository {<br>    get(filter: string): Promise&lt;Either&lt;DataError, Product[]&gt;&gt;;<br>}</pre><h3>Data Layer</h3><p>The data layer is where the adapters are found and an adapter is responsible to transform the information between the domain and external systems.</p><p>External systems may be a web service, a database, etc…</p><p>In this simple example, I’m using the same entities that represent the product, shopping cart, and cart items between the presentation, domain, and data layers.</p><p>In real applications, is common to have a different data structure for each layer or even to have Data Transfer Objects (DTOs) to pass data between layers.</p><p>In this example, we have repositories that return data stored in memory.</p><pre>const products = [<br>  ...<br>];</pre><pre>export class ProductInMemoryRepository implements ProductRepository {<br>    get(filter: string): Promise&lt;Either&lt;DataError, Product[]&gt;&gt; {<br>        return new Promise((resolve, _reject) =&gt; {<br>            setTimeout(() =&gt; {<br>                try {<br>                    if (filter) {<br>                        const filteredProducts = products.filter((p: Product) =&gt; {<br>                            return p.title.toLowerCase().includes(filter.toLowerCase());<br>                        });</pre><pre>resolve(Either.right(filteredProducts));<br>                    } else {<br>                        resolve(Either.right(products));<br>                    }<br>                } catch (error) {<br>                    resolve(Either.left(error));<br>                }<br>            }, 100);<br>        });<br>    }<br>}</pre><p>The important thing is to understand that the repository is an adapter and that its abstraction or port is defined in the domain, so the traditional direction of the dependency is inverted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*ZV9tRL1KrontbBgRtS8Cqg.png" /><figcaption>Dependency inversion</figcaption></figure><p>This is the most important part of Clean Architecture, <strong>the domain should not have any dependency on external layers</strong>, in this way it is uncoupled and it will be easier to replace an adapter with another in the future or even for testing purposes.</p><p>In this way, if we replace the adapter implementation with one that invokes a web service, the domain is not affected and therefore we are hiding implementation details.</p><h3>Presentation Layer — Adapters</h3><p>The adapters of the presentation layer are the last reuse part of our core package and It’s where we hook the UI React or Vue layers.</p><p>These adapters are also reusable between the two versions of the app, they are intermediaries between the UI components and the domain layer.</p><p>They contain the presentation logic, deciding what information is shown, what should be visible, etc…</p><p><strong>The state management is performed by this layer </strong>and does not depend on React or Vue.</p><p>There are different presentation patterns that we can use. In this case, I am using the BLoC Pattern because it fits very well with declarative frameworks such as React and Vue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*leLTYWOjc2ArBFoYnH7OnQ.png" /><figcaption>BLoC Pattern</figcaption></figure><p>If you want to delve into the BLoC pattern, I recommend that you read this <a href="http://xurxodev.com/introduccion-al-patron-bloc/">article</a>.</p><p>As I discussed in that article, when you use BLoC with Clean Architecture, it makes more sense to call them PLoC,<strong> Presentation Logic Component</strong>. So in this example, they are named this way.</p><p>Let’s see the shopping cart example:</p><pre>export class CartPloc extends Ploc&lt;CartState&gt; {<br>    constructor(<br>        private getCartUseCase: GetCartUseCase,<br>        private addProductToCartUseCase: AddProductToCartUseCase,<br>        private removeItemFromCartUseCase: RemoveItemFromCartUseCase,<br>        private editQuantityOfCartItemUseCase: EditQuantityOfCartItemUseCase<br>    ) {<br>        super(cartInitialState);<br>        this.loadCart();<br>    }</pre><pre>closeCart() {<br>        this.changeState({ ...this.state, open: false });<br>    }</pre><pre>openCart() {<br>        this.changeState({ ...this.state, open: true });<br>    }</pre><pre>removeCartItem(item: CartItemState) {<br>        this.removeItemFromCartUseCase<br>            .execute(item.id)<br>            .then(cart =&gt; this.changeState(this.mapToUpdatedState(cart)));<br>    }</pre><pre>editQuantityCartItem(item: CartItemState, quantity: number) {<br>        this.editQuantityOfCartItemUseCase<br>            .execute(item.id, quantity)<br>            .then(cart =&gt; this.changeState(this.mapToUpdatedState(cart)));<br>    }</pre><pre>addProductToCart(product: Product) {<br>        this.addProductToCartUseCase<br>            .execute(product)<br>            .then(cart =&gt; this.changeState(this.mapToUpdatedState(cart)));<br>    }</pre><pre>private loadCart() {<br>        this.getCartUseCase<br>            .execute()<br>            .then(cart =&gt; this.changeState(this.mapToUpdatedState(cart)))<br>            .catch(() =&gt;<br>                this.changeState({<br>                    kind: &quot;ErrorCartState&quot;,<br>                    error: &quot;An error has ocurred loading products&quot;,<br>                    open: this.state.open,<br>                })<br>            );<br>    }</pre><pre>mapToUpdatedState(cart: Cart): CartState {<br>        const formatOptions = { style: &quot;currency&quot;, currency: &quot;EUR&quot; };</pre><pre>return {<br>            kind: &quot;UpdatedCartState&quot;,<br>            open: this.state.open,<br>            totalItems: cart.totalItems,<br>            totalPrice: cart.totalPrice.toLocaleString(&quot;es-ES&quot;, formatOptions),<br>            items: cart.items.map(cartItem =&gt; {<br>                return {<br>                    id: cartItem.id,<br>                    image: cartItem.image,<br>                    title: cartItem.title,<br>                    price: cartItem.price.toLocaleString(&quot;es-ES&quot;, formatOptions),<br>                    quantity: cartItem.quantity,<br>                };<br>            }),<br>        };<br>    }<br>}</pre><p>The base class of all PLoCs is responsible for storing the state and notifying when it changes.</p><pre>type Subscription&lt;S&gt; = (state: S) =&gt; void;</pre><pre>export abstract class Ploc&lt;S&gt; {<br>    private internalState: S;<br>    private listeners: Subscription&lt;S&gt;[] = [];</pre><pre>constructor(initalState: S) {<br>        this.internalState = initalState;<br>    }</pre><pre>public get state(): S {<br>        return this.internalState;<br>    }</pre><pre>changeState(state: S) {<br>        this.internalState = state;</pre><pre>if (this.listeners.length &gt; 0) {<br>            this.listeners.forEach(listener =&gt; listener(this.state));<br>        }<br>    }</pre><pre>subscribe(listener: Subscription&lt;S&gt;) {<br>        this.listeners.push(listener);<br>    }</pre><pre>unsubscribe(listener: Subscription&lt;S&gt;) {<br>        const index = this.listeners.indexOf(listener);<br>        if (index &gt; -1) {<br>            this.listeners.splice(index, 1);<br>        }<br>    }<br>}</pre><p>All the information that the UI component needs must be interpreted from the state, elements to render in a table or list, but also if something should be visible or not, such as the shopping cart, the loading, or an error to show.</p><pre>export interface CommonCartState {<br>    open: boolean;<br>}</pre><pre>export interface LoadingCartState {<br>    kind: &quot;LoadingCartState&quot;;<br>}</pre><pre>export interface UpdatedCartState {<br>    kind: &quot;UpdatedCartState&quot;;<br>    items: Array&lt;CartItemState&gt;;<br>    totalPrice: string;<br>    totalItems: number;<br>}</pre><pre>export interface ErrorCartState {<br>    kind: &quot;ErrorCartState&quot;;<br>    error: string;<br>}</pre><pre>export type CartState = (LoadingCartState | UpdatedCartState | ErrorCartState) &amp; CommonCartState;</pre><pre>export interface CartItemState {<br>    id: string;<br>    image: string;<br>    title: string;<br>    price: string;<br>    quantity: number;<br>}</pre><pre>export const cartInitialState: CartState = {<br>    kind: &quot;LoadingCartState&quot;,<br>    open: false,<br>};</pre><p>In this case through union types of typescript, we can more securely and functionally model our state using <a href="https://xurxodev.com/tipos-de-datos-algebraicos-sum-en-typescript/">sum algebraic data types</a>.</p><p>This way of modeling is less prone to errors because you indicate that a very clear form that the state has 3 main possibilities:</p><ul><li>Loading information</li><li>An error has occurred</li><li>Updated data</li></ul><h3>Presentation Layer — UI</h3><p>In this layer is where are the components and everything related to React or Vue such as components, hooks, applications, etc.</p><p>The components are very simple and light because they are free to manage any type of logic or state management, this is the responsibility of each of the layers in the core package.</p><h4>React App</h4><p>In react we will have the components that render our list of products, the app bar with the number of products in the cart, and the product cart rendered as a Sidebar.</p><p>Let’s see the example of the component that renders the content of the cart.</p><pre>import React from &quot;react&quot;;<br>import { makeStyles, Theme } from &quot;<a href="http://twitter.com/material">@material</a>-ui/core/styles&quot;;<br>import { List, Divider, Box, Typography, CircularProgress } from &quot;<a href="http://twitter.com/material">@material</a>-ui/core&quot;;<br>import CartContentItem from &quot;./CartContentItem&quot;;<br>import { CartItemState } from &quot;<a href="http://twitter.com/frontend">@frontend</a>-clean-architecture/core&quot;;<br>import { useCartPloc } from &quot;../app/App&quot;;<br>import { usePlocState } from &quot;../common/usePlocState&quot;;</pre><pre>const useStyles = makeStyles((theme: Theme) =&gt; ({<br>    totalPriceContainer: {<br>        display: &quot;flex&quot;,<br>        alignItems: &quot;center&quot;,<br>        padding: theme.spacing(1, 0),<br>        justifyContent: &quot;space-around&quot;,<br>    },<br>    itemsContainer: {<br>        display: &quot;flex&quot;,<br>        alignItems: &quot;center&quot;,<br>        padding: theme.spacing(1, 0),<br>        justifyContent: &quot;space-around&quot;,<br>        minHeight: 150,<br>    },<br>    itemsList: {<br>        overflow: &quot;scroll&quot;,<br>    },<br>    infoContainer: {<br>        display: &quot;flex&quot;,<br>        alignItems: &quot;center&quot;,<br>        justifyContent: &quot;center&quot;,<br>        height: &quot;100vh&quot;,<br>    },<br>}));</pre><pre>const CartContent: React.FC = () =&gt; {<br>    const classes = useStyles();<br>    const ploc = useCartPloc();<br>    const state = usePlocState(ploc);</pre><pre>const cartItems = (items: CartItemState[]) =&gt; (<br>        &lt;List className={classes.itemsList}&gt;<br>            {items.map((item, index) =&gt; (<br>                &lt;CartContentItem key={index} cartItem={item} /&gt;<br>            ))}<br>        &lt;/List&gt;<br>    );</pre><pre>const emptyCartItems = () =&gt; (<br>        &lt;React.Fragment&gt;<br>            &lt;Typography variant=&quot;h6&quot; component=&quot;h2&quot;&gt;<br>                Empty Cart :(<br>            &lt;/Typography&gt;<br>        &lt;/React.Fragment&gt;<br>    );</pre><pre>switch (state.kind) {<br>        case &quot;LoadingCartState&quot;: {<br>            return (<br>                &lt;div className={classes.infoContainer}&gt;<br>                    &lt;CircularProgress /&gt;<br>                &lt;/div&gt;<br>            );<br>        }<br>        case &quot;ErrorCartState&quot;: {<br>            return (<br>                &lt;div className={classes.infoContainer}&gt;<br>                    &lt;Typography display=&quot;inline&quot; variant=&quot;h5&quot; component=&quot;h2&quot;&gt;<br>                        {state.error}<br>                    &lt;/Typography&gt;<br>                &lt;/div&gt;<br>            );<br>        }<br>        case &quot;UpdatedCartState&quot;: {<br>            return (<br>                &lt;React.Fragment&gt;<br>                    &lt;Box flexDirection=&quot;column&quot; className={classes.itemsContainer}&gt;<br>                        {state.items.length &gt; 0 ? cartItems(state.items) : emptyCartItems()}<br>                    &lt;/Box&gt;<br>                    &lt;Divider /&gt;<br>                    &lt;Box flexDirection=&quot;row&quot; className={classes.totalPriceContainer}&gt;<br>                        &lt;Typography variant=&quot;h6&quot; component=&quot;h2&quot;&gt;<br>                            Total Price<br>                        &lt;/Typography&gt;<br>                        &lt;Typography variant=&quot;h6&quot; component=&quot;h2&quot;&gt;<br>                            {state.totalPrice}<br>                        &lt;/Typography&gt;<br>                    &lt;/Box&gt;<br>                &lt;/React.Fragment&gt;<br>            );<br>        }<br>    }<br>};</pre><pre>export default CartContent;</pre><h4>Hooks</h4><p>Using Clean Architecture, hooks are not used? Yes, they are used, but for what is strictly necessary.</p><p>The state will not be managed with hooks, the side effects are not triggered from hooks, this is the responsibility of the PloCs in the core package.</p><p>But we will use them to store the final state of the component that its PloC returns to us and we will use them to share context between components or react to the change of state that the PloC returns to us.</p><p>Let’s see how the usePLocState hook that we used in the component is defined:</p><pre>export function usePlocState&lt;S&gt;(ploc: Ploc&lt;S&gt;) {<br>    const [state, setState] = useState(ploc.state);</pre><pre>useEffect(() =&gt; {<br>        const stateSubscription = (state: S) =&gt; {<br>            setState(state);<br>        };</pre><pre>ploc.subscribe(stateSubscription);</pre><pre>return () =&gt; ploc.unsubscribe(stateSubscription);<br>    }, [ploc]);</pre><pre>return state;<br>}</pre><p>This custom hook is in charge of subscribing to the PloC state changes and storing the final state.</p><h4>Vue App</h4><p>In Vue, we will also have the same components as in the React version.</p><p>Now let’s see the component that renders the content of the shopping cart in the Vue version:</p><pre>&lt;template&gt;<br>    &lt;div id=&quot;info-container&quot; v-if=&quot;state.kind === &#39;LoadingCartState&#39;&quot;&gt;<br>        &lt;ProgressSpinner /&gt;<br>    &lt;/div&gt;<br>    &lt;div id=&quot;info-container&quot; v-if=&quot;state.kind === &#39;ErrorCartState&#39;&quot;&gt;Error&lt;/div&gt;<br>    &lt;div id=&quot;items-container&quot; v-if=&quot;state.kind === &#39;UpdatedCartState&#39;&quot;&gt;<br>        &lt;div v-if=&quot;state.items.length &gt; 0&quot; style=&quot;overflow: scroll&quot;&gt;<br>            &lt;div v-for=&quot;item in state.items&quot; v-bind:key=&quot;item.id&quot;&gt;<br>                &lt;CartContenttItem v-bind=&quot;item&quot; /&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;h2 v-if=&quot;state.items.length === 0&quot;&gt;Empty Cart :(&lt;/h2&gt;<br>    &lt;/div&gt;<br>    &lt;Divider /&gt;<br>    &lt;div id=&quot;total-price-container&quot;&gt;<br>        &lt;h3&gt;Total Price&lt;/h3&gt;<br>        &lt;h3&gt;{{ state.totalPrice }}&lt;/h3&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script lang=&quot;ts&quot;&gt;<br>import { defineComponent, inject } from &quot;vue&quot;;<br>import { CartPloc } from &quot;<a href="http://twitter.com/frontend">@frontend</a>-clean-architecture/core&quot;;<br>import { usePlocState } from &quot;../common/usePlocState&quot;;<br>import CartContenttItem from &quot;./CartContenttItem.vue&quot;;</pre><pre>export default defineComponent({<br>    components: {<br>        CartContenttItem,<br>    },<br>    setup() {<br>        const ploc = inject&lt;CartPloc&gt;(&quot;cartPloc&quot;) as CartPloc;<br>        const state = usePlocState(ploc);</pre><pre>return { state };<br>    },<br>});<br>&lt;/script&gt;</pre><pre>&lt;style scoped&gt;<br>#info-container {<br>    display: flex;<br>    align-items: center;<br>    justify-content: center;<br>    height: 100vh;<br>}<br>#items-container {<br>    display: flex;<br>    flex-direction: column;<br>    align-items: center;<br>    min-height: 150px;<br>    justify-content: space-around;<br>}<br>#total-price-container {<br>    display: flex;<br>    align-items: center;<br>    padding: 8px 0px;<br>    justify-content: space-around;<br>}<br>&lt;/style&gt;</pre><p>As you can see, it looks a lot like the React version using composition API.</p><h4>Composition API</h4><p>In the Vue version we will also have hooks, such as the one that manages the subscription to changes in the PLoC state:</p><pre>import { Ploc } from &quot;<a href="http://twitter.com/frontend">@frontend</a>-clean-architecture/core&quot;;</pre><pre>import { DeepReadonly, onMounted, onUnmounted, readonly, Ref, ref } from &quot;vue&quot;;</pre><pre>export function usePlocState&lt;S&gt;(ploc: Ploc&lt;S&gt;): DeepReadonly&lt;Ref&lt;S&gt;&gt; {<br>    const state = ref(ploc.state) as Ref&lt;S&gt;;</pre><pre>const stateSubscription = (newState: S) =&gt; {<br>        state.value = newState;<br>    };</pre><pre>onMounted(() =&gt; {<br>        ploc.subscribe(stateSubscription);<br>    });</pre><pre>onUnmounted(() =&gt; {<br>        ploc.unsubscribe(stateSubscription);<br>    });</pre><pre>return readonly(state);<br>}</pre><h3>Dependency Injection</h3><p>From the React and Vue app, we have to create or reuse the PloC structure for each component: use cases and repositories.</p><p>If these concepts were defined in the core package, the part responsible for creating them may be in the core package as well.</p><p>This time I am using the Service Locator pattern statically:</p><pre>function provideProductsPloc(): ProductsPloc {<br>    const productRepository = new ProductInMemoryRepository();<br>    const getProductsUseCase = new GetProductsUseCase(productRepository);<br>    const productsPloc = new ProductsPloc(getProductsUseCase);</pre><pre>return productsPloc;<br>}</pre><pre>function provideCartPloc(): CartPloc {<br>    const cartRepository = new CartInMemoryRepository();<br>    const getCartUseCase = new GetCartUseCase(cartRepository);<br>    const addProductToCartUseCase = new AddProductToCartUseCase(cartRepository);<br>    const removeItemFromCartUseCase = new RemoveItemFromCartUseCase(cartRepository);<br>    const editQuantityOfCartItemUseCase = new EditQuantityOfCartItemUseCase(cartRepository);<br>    const cartPloc = new CartPloc(<br>        getCartUseCase,<br>        addProductToCartUseCase,<br>        removeItemFromCartUseCase,<br>        editQuantityOfCartItemUseCase<br>    );</pre><pre>return cartPloc;<br>}</pre><pre>export const dependenciesLocator = {<br>    provideProductsPloc,<br>    provideCartPloc,<br>};</pre><p>We could also use a <a href="http://xurxodev.com/inyeccion-de-dependencias-typescript-service-locator/">dynamic Service Locator together with Composition Root</a> or a dependency injection library.</p><p>In the React app, there is a global state that must be shared, it is the shopping cart. Therefore CartPloc, which is the one who manages this state, must be shared and accessible by all components.</p><h4>React</h4><p>In React we solve this using createContext and a custom hook using useContext.</p><pre>export function createContext&lt;T&gt;() {<br>    const context = React.createContext&lt;T | undefined&gt;(undefined);</pre><pre>function useContext() {<br>        const ctx = React.useContext(context);<br>        if (!ctx) throw new Error(&quot;context must be inside a Provider with a value&quot;);<br>        return ctx;<br>    }<br>    return [context, useContext] as const;<br>}</pre><pre>const [blocContext, usePloc] = createContext&lt;CartPloc&gt;();</pre><pre>export const useCartPloc = usePloc;</pre><pre>const App: React.FC = () =&gt; {<br>    return (<br>        &lt;blocContext.Provider value={dependenciesLocator.provideCartPloc()}&gt;<br>            &lt;MyAppBar /&gt;<br>            &lt;ProductList /&gt;<br>            &lt;CartDrawer /&gt;<br>        &lt;/blocContext.Provider&gt;<br>    );<br>};</pre><pre>export default App;</pre><p>Using the custom useCartPloc we have access from any component to this PloC and its state.</p><h4>Vue App</h4><p>In Vue, we solve this by using the provide feature.</p><pre>&lt;template&gt;<br>    &lt;div id=&quot;app&quot;&gt;<br>        &lt;MyAppBar /&gt;<br>        &lt;ProductList searchTerm=&quot;Element&quot; /&gt;<br>        &lt;CartSidebar /&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script lang=&quot;ts&quot;&gt;<br>import { dependenciesLocator } from &quot;<a href="http://twitter.com/frontend">@frontend</a>-clean-architecture/core&quot;;<br>import { defineComponent } from &quot;vue&quot;;<br>import MyAppBar from &quot;./appbar/MyAppBar.vue&quot;;<br>import ProductList from &quot;./products/ProductList.vue&quot;;<br>import CartSidebar from &quot;./cart/CartSidebar.vue&quot;;</pre><pre>export default defineComponent({<br>    name: &quot;App&quot;,<br>    components: {<br>        ProductList,<br>        MyAppBar,<br>        CartSidebar,<br>    },<br>    provide: {<br>        cartPloc: dependenciesLocator.provideCartPloc(),<br>    },<br>});<br>&lt;/script&gt;</pre><p>Later from any component, we have access to the PLoC and its state using:</p><pre>const cartPloc = inject &lt;CartPloc&gt; (“cartPloc”) as CartPloc;</pre><h3>Source code</h3><p>The source code can be found here: <a href="https://github.com/xurxodev/frontend-clean-architecture">frontend-clean-architecture</a>.</p><p>Related Articles And Resources</p><ul><li><a href="https://www.amazon.es/gp/product/0134494164?tag=xurxodev0e-21">Clean Architecture: A Craftsman’s Guide to Software Structure and Design</a></li><li><a href="http://xurxodev.com/curso-clean-architecture">Clean Architecture Course</a>.</li><li><a href="http://xurxodev.com/por-que-utilizo-clean-architecture-en-mis-proyectos/">¿Wy use I Clean Architecture in my projects?</a></li><li><a href="http://xurxodev.com/el-patron-bloc-en-clean-architecture/">The Bloc Pattern in Clean Architecture</a></li><li><a href="http://xurxodev.com/el-patron-bloc-junto-a-clean-architecture-en-reactjs/">The BLoC Pattern in Clean Architecture in ReactJS</a></li><li>T<a href="http://xurxodev.com/el-patron-bloc-junto-a-clean-architecture-en-flutter/">he BLoC Pattern in Clean Architecture in Flutter</a></li><li><a href="http://xurxodev.com/clean-architecture-code-smells-parte-1/">Clean Architecture: Code Smells. Parte 1</a></li><li><a href="http://xurxodev.com/clean-architecture-code-smells-parte-2/">Clean Architecture: Code Smells. Parte 2</a></li><li><a href="http://xurxodev.com/mi-surrealista-compra-del-libro-clean-architecture/">My surreal purchase of the book Clean Architecture</a></li></ul><h3>Conclusions</h3><p>In this article, we have seen a Clean Architecture implementation on the front-end.</p><p>We have a version of React and Vue app reusing as much code as possible between the two and placing it in a core package.</p><p>With this exercise of having a core package with all the logic uncoupled from the framework, we can appreciate the power that Clean Architecture can offer us on the front-end.</p><p>Organizing the project as a monorepo and having a core package has been necessary for this example, but it is not necessary when developing an app either React or Vue.</p><p>However, it is an interesting exercise to force you to uncouple from the UI framework as it can sometimes be difficult to see that you are coupling, especially at the beginning.</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca2592bd9d58" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/frontend-clean-architecture-ca2592bd9d58">Moving Away from React and Vue.js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a REST API client and its integration tests in Flutter]]></title>
            <link>https://medium.com/flutter-community/how-to-create-a-rest-api-client-and-its-integration-tests-in-flutter-924f71e23e0d?source=rss-c3fe54d1497b------2</link>
            <guid isPermaLink="false">https://medium.com/p/924f71e23e0d</guid>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Jorge Sánchez (xurxodev)]]></dc:creator>
            <pubDate>Fri, 06 Mar 2020 15:56:08 GMT</pubDate>
            <atom:updated>2023-07-11T15:15:37.190Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XFM3x8g1WypeGsXk47L-gw.png" /><figcaption>API Integration testing in Flutter</figcaption></figure><p>This article is an English translation from my original article in my blog <a href="http://xurxodev.com/como-crear-un-cliente-api-rest-y-sus-tests-de-integracion-en-flutter">xurxodev.com</a>.</p><p>Subscribe to my Spanish newsletter where I write stories about my vision of the software development: <a href="https://xurxodev.com/#/portal/signup">https://xurxodev.com/#/portal/signup</a></p><p>Most of the mobile applications are based on communication with an API Rest.</p><p>The integration with an external service is fundamental in mobile development. To have an optimal integration, it is necessary to ensure it by integration tests.</p><p>One year ago I wrote about this topic though it was applied to <a href="https://blog.kotlin-academy.com/how-to-create-a-rest-api-client-and-its-integration-tests-in-kotlin-multiplatform-d76c9a1be348">Kotlin multiplatform</a>.</p><p>I have been working with <a href="http://xurxodev.com/tag/flutter/">Flutter for some time</a> and I felt it was high time to write about this topic applied to Flutter.</p><p>In this article, we will see how to create a REST API client and its integration tests in Flutter necessary to verify that our integration works.</p><h3>API REST</h3><p>The client that we are going to create communicates with the following web service:</p><p><a href="http://jsonplaceholder.typicode.com/">http://jsonplaceholder.typicode.com/</a></p><p>This REST API manages tasks, so you will be able to:</p><p>get all the existing tasks, get a task by identifier, add a new task, update a task or delete an existing task.</p><h3>Creating the project</h3><p>The first thing to do is to create the project. You can use Android Studio or Visual Studio Code.</p><p>Details on how to install Flutter and how to configure it to work is out of the scope of this post.</p><p>Here you have Flutter’s official documentation:<a href="https://flutter-es.io/docs/get-started/install"> Flutter get-started</a>.</p><h3>Setting up the continuous integration</h3><p>The best time to set up CI for a project is the beginning, so this would be the next step.</p><p>I’ve used<a href="https://codemagic.io/"> Codemagic</a>. It is the continuous integration tool that I like the most for Flutter due to its simplicity with bare setup.</p><p>It’s only focused on Flutter; that’s the reason why it is very easy.</p><p>It is possible to make the set up through its website or through a YAML file.</p><p>Here I am leaving Codemagic documentation for the set up:<a href="https://docs.codemagic.io/getting-started/getting-started/"> Codemagic get-started</a>.</p><h3>Creating the client</h3><h4>Packages to use</h4><p>In Flutter the libraries are named as packages and we are going to need:</p><ul><li><a href="https://pub.dev/packages/http">Http</a>, It’s a package developed by the Flutter team to make requests to a remote server. It would be like Retrofit for Android or Alamofire and AFNetworking for iOS.</li></ul><h4>TodoApiClient</h4><p>Our client will be composed of an HTTP client, to which we will make the requests and receive the base address in the constructor. We will see why later.</p><p>We need to handle the errors that the API returns. On this occasion, we will generate an exception for each error.</p><p>In a future article, we will see how to do it in a more functional style by using an Either type as a return value. This strategy is equal to the one we used in the version of Kotlin multiplatform that I wrote last year.</p><pre>class TodoApiClient {<br>    ...<br>    <br>    http.Response returnResponseOrThrowException(http.Response response) {<br>    if (response.statusCode == 404) {<br>      throw ItemNotFoundException();<br>    } else if (response.statusCode &gt; 400) {<br>      throw UnKnowApiException(response.statusCode);<br>    } else {<br>      return response;<br>    }<br>  }<br>  <br>  ...<br>}</pre><p>In this class, we need some infrastructure. We will have a private method for each verb where we will make the request to the corresponding endpoint, we will assign headers and body if applicable.</p><pre>class TodoApiClient {<br>  final String _baseAddress;</pre><pre>TodoApiClient(this._baseAddress);</pre><pre>...<br> <br>  Future&lt;http.Response&gt; _get(String endpoint) async {<br>    try {<br>      final response = await http.get(<br>        &#39;$_baseAddress$endpoint&#39;,<br>        headers: {<br>          HttpHeaders.acceptHeader: &#39;application/json&#39;,<br>        },<br>      );</pre><pre>return returnResponseOrThrowException(response);<br>    } on IOException catch (e) {<br>      print(e.toString());<br>      throw NetworkException();<br>    }<br>  }</pre><pre>Future&lt;http.Response&gt; _post(Task task) async {<br>    try {<br>      final response = await http.post(<br>        &#39;$_baseAddress/todos&#39;,<br>        body: json.encode(task.toJson()) ,<br>        headers: {<br>          HttpHeaders.acceptHeader: &#39;application/json&#39;,<br>          HttpHeaders.contentTypeHeader: &#39;application/json&#39;,<br>        },<br>      );</pre><pre>return returnResponseOrThrowException(response);<br>    } on IOException {<br>      throw NetworkException();<br>    }<br>  }</pre><pre>Future&lt;http.Response&gt; _put(Task task) async {<br>    try {<br>      final response = await http.put(<br>        &#39;$_baseAddress/todos/${task.id}&#39;,<br>        body: json.encode(task.toJson()) ,<br>        headers: {<br>          HttpHeaders.acceptHeader: &#39;application/json&#39;,<br>          HttpHeaders.contentTypeHeader: &#39;application/json&#39;,<br>        },<br>      );</pre><pre>return returnResponseOrThrowException(response);<br>    } on IOException  {<br>      throw NetworkException();<br>    }<br>  }</pre><pre>Future&lt;http.Response&gt; _delete(String id) async {<br>    try {<br>      final response = await http.delete(<br>        &#39;$_baseAddress/todos/$id&#39;,<br>        headers: {<br>          HttpHeaders.acceptHeader: &#39;application/json&#39;,<br>        },<br>      );</pre><pre>return returnResponseOrThrowException(response);<br>    } on IOException  {<br>      throw NetworkException();<br>    }<br>  }<br>  <br>  ...</pre><pre>}</pre><p>We will have a method for each of the actions in the remote service.</p><pre>class TodoApiClient {</pre><pre>...<br>    <br>  Future&lt;List&lt;Task&gt;&gt; getAllTasks() async {<br>    final response = await _get(&#39;/todos&#39;);</pre><pre>final decodedTasks = json.decode(response.body) as List;</pre><pre>return decodedTasks.map((jsonTask) =&gt; Task.fromJson(jsonTask)).toList();<br>  }</pre><pre>Future&lt;Task&gt; getTasksById(String id) async {<br>    final response = await _get(&#39;/todos/$id&#39;);</pre><pre>return Task.fromJson(json.decode(response.body));<br>  }</pre><pre>Future&lt;Task&gt; addTask(Task task) async {<br>    final response = await _post(task);</pre><pre>return Task.fromJson(json.decode(response.body));<br>  }</pre><pre>Future&lt;Task&gt; updateTask(Task task) async {<br>    final response = await _put(task);</pre><pre>return Task.fromJson(json.decode(response.body));<br>  }</pre><pre>Future&lt;void&gt; deleteTaskById(String id) async {<br>    await _delete(id);<br>  }<br>  <br>    ...<br>}</pre><p>About serialization, flutter is disabled and there are two options:</p><ul><li>Manual serialization, suitable for small projects like the one I created for this example.</li><li>Serialization through code generation, for medium or large projects.</li></ul><p>Here I am leaving a link to the Flutter documentation about serialization so you can expand on this point:<a href="https://flutter-es.io/docs/development/data-and-backend/json"> Flutter serialization</a>.</p><h3>Integration tests</h3><p>To test the integration of our client with the Rest API, we need to verify the following:</p><ul><li>The requests are sent correctly to the API: endpoint, verb, headers, body if applicable.</li><li>The server responses are parsed correctly.</li><li>The server error responses are handled correctly.</li></ul><p>To perform these checks we have to simulate server responses and to be able to access in some way to the HTTP requests that we have sent.</p><h4>Packages to use</h4><p>There are two possible strategies at this point:</p><ul><li><strong>Use an HTTP client mock</strong>, the flutter HTTP package provides a MockClient class to do this. This client should be passed as an argument to our TodoApiClient. But this mock client is a bit limited for more complex scenarios, where a call to TodoApiClient involves several calls to the server. (for example, to renew the token). For simple examples, this option is valid.</li><li><strong>Use a mock server,</strong> this is the option I usually use. The idea is to start an embedded HTTP server. We can configure our responses and validate the sent requests. The mock server URL must be passed as an argument in the TodoApiClient constructor.</li></ul><p>We need the next package:</p><ul><li><a href="https://pub.dev/packages/mock_web_server">mock-web-server</a>, is based on the<a href="https://github.com/square/okhttp/tree/master/mockwebserver"> library</a> with the same name created by Square for Java.</li></ul><h4>Creating the tests</h4><p>Let’s see some tests that we can create.</p><p>The first tests we could try are to verify the todos endpoint, for example:</p><ul><li>To verify the response is parsed correctly.</li><li>To verify that accept header is sent.</li><li>To verify in case of an error, it is processed properly.</li></ul><p>What infrastructure do we need? We need to have a way to enqueue responses on the mock server and verify the sent request. We will pass the mock server URL as an argument in the TodoApiClient constructor.</p><p>We need a JSON that represents the server’s response:</p><pre>// get_tasks_response.json<br>[<br>  {<br>    &quot;userId&quot;: 1,<br>    &quot;id&quot;: 1,<br>    &quot;title&quot;: &quot;delectus aut autem&quot;,<br>    &quot;completed&quot;: false<br>  },<br>  {<br>    &quot;userId&quot;: 1,<br>    &quot;id&quot;: 2,<br>    &quot;title&quot;: &quot;quis ut nam facilis et officia qui&quot;,<br>    &quot;completed&quot;: false<br>  },<br>  {<br>    &quot;userId&quot;: 1,<br>    &quot;id&quot;: 3,<br>    &quot;title&quot;: &quot;fugiat veniam minus&quot;,<br>    &quot;completed&quot;: false<br>  }<br>]</pre><p>Now we need to be able to read this file and enqueue it as the next mock server response, then to get the last request against the mock server to validate it.</p><p>We can create a base class for our tests or create a specific class to realize this work. I like to <a href="http://xurxodev.com/favoreciendo-la-composicion-sobre-la-herencia-tambien-en-los-test/">favour the composition over the inheritance also in the tests</a>.</p><pre>class MockApi {<br>  MockWebServer _server;</pre><pre>Future&lt;void&gt; start() async {<br>    _server = MockWebServer();<br>    await _server.start();<br>  }</pre><pre>void shutdown() {<br>    _server.shutdown();<br>  }</pre><pre>String get baseAddress =&gt; _server.url.substring(0, _server.url.length - 1);</pre><pre>Future&lt;void&gt; enqueueMockResponse(<br>      {String fileName = &#39;&#39;,<br>      int httpCode = 200,<br>      Map&lt;String, String&gt; headers}) async {<br>    final content = await _getContentFromFile(fileName: fileName);</pre><pre>_server.enqueue(body: content, httpCode: httpCode, headers: headers);<br>  }</pre><pre>void expectRequestSentTo(String endpoint) {<br>    final StoredRequest storedRequest = _server.takeRequest();</pre><pre>expect(storedRequest.uri.path, endpoint);<br>  }</pre><pre>void expectRequestContainsHeader([String key, String expectedValue, int requestIndex = 0]) {<br>    final StoredRequest storedRequest = _getRecordedRequestAtIndex(requestIndex);<br>    final value = storedRequest.headers[key];</pre><pre>expect(value, contains(expectedValue));<br>  }</pre><pre>Future&lt;void&gt; expectRequestContainsBody(String fileName) async {<br>    final expectedBody = await _getContentFromFile(fileName: fileName);<br>    final StoredRequest storedRequest = _getRecordedRequestAtIndex(0);</pre><pre>expect(storedRequest.body, expectedBody);<br>  }</pre><pre>...<br>}</pre><p>This class is a wrapper on the mock server.</p><p>This class add specific infrastructure to our needs:</p><ul><li>enqueue a response reading the contents from a file</li><li>performing validations about the endpoint, headers and body in the request made to the mock server.</li></ul><p>And finally, we write our tests:</p><pre>TodoApiClient _todoApiClient;<br>MockApi mockApi = MockApi();<br>String anyTaskId = &#39;1&#39;;<br>Task anyTask =<br>    Task(id: 1, userId: 1, title: &#39;Finish this kata&#39;, completed: false);</pre><pre>void main() {<br>  setUp(() async {<br>    await mockApi.start();</pre><pre>_todoApiClient = TodoApiClient(mockApi.baseAddress);<br>  });</pre><pre>tearDown(() {<br>    mockApi.shutdown();<br>  });</pre><pre>group(&#39;TodoApiClient&#39;, () {</pre><pre>group(&#39;GetAllTasks should&#39;, () {</pre><pre>test(&#39;sends get request to the correct endpoint&#39;, () async {<br>        await mockApi.enqueueMockResponse(fileName: getTasksResponse);</pre><pre>await _todoApiClient.getAllTasks();</pre><pre>mockApi.expectRequestSentTo(&#39;/todos&#39;);<br>      });</pre><pre>test(&#39;sends accept header&#39;, () async {<br>        await mockApi.enqueueMockResponse(fileName: getTasksResponse);</pre><pre>await _todoApiClient.getAllTasks();</pre><pre>mockApi.expectRequestContainsHeader(&#39;accept&#39;, &#39;application/json&#39;);<br>      });</pre><pre>test(&#39;parse current news properly getting all current news&#39;, () async {<br>        await mockApi.enqueueMockResponse(fileName: getTasksResponse);</pre><pre>final tasks = await _todoApiClient.getAllTasks();</pre><pre>expectTasksContainsExpectedValues(tasks[0]);<br>      });</pre><pre>test(<br>          &#39;throws UnknownErrorException if there is not handled error getting news&#39;,<br>          () async {<br>        await mockApi.enqueueMockResponse(httpCode: 454);</pre><pre>expect(() =&gt; _todoApiClient.getAllTasks(),<br>            throwsA(isInstanceOf&lt;UnKnowApiException&gt;()));<br>      });<br>    });<br>    <br>    ...<br>    <br>  });<br>}</pre><pre>void expectTasksContainsExpectedValues(Task task) {<br>  expect(task, isNotNull);<br>  expect(task.userId, 1);<br>  expect(task.id, 1);<br>  expect(task.title, &#39;delectus aut autem&#39;);<br>  expect(task.completed, false);<br>}</pre><p>As you can see, to write test on Flutter is very similar to Javascript with Jest for example.</p><h3>Kata and source code</h3><p>You can find the source code <a href="https://github.com/xurxodev/api-integration-testing-flutter-kata">here</a>.</p><p>The master branch contains all the kata solved by me.</p><p>The best way to learn is by practising so I recommend using the <a href="https://github.com/xurxodev/api-integration-testing-flutter-kata/tree/api-integration-testing-flutter-kata">kata branch</a> and doing the exercise by yourself.</p><h3>Related Course</h3><p><a href="http://xurxodev.com/curso-testing/">Testing Course</a></p><h3>Conclusions</h3><p>In this post, we have seen how to create a REST API client on Flutter. Also how to create tests that allow us to validate the integration with the remote service.</p><p><strong>Thanks for reading this article! If you liked it, press the 👏🏼 button so other people can read it too :)</strong></p><p><a href="https://www.twitter.com/FlutterComm">JavaScript is not available.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=924f71e23e0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/how-to-create-a-rest-api-client-and-its-integration-tests-in-flutter-924f71e23e0d">How to create a REST API client and its integration tests in Flutter</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a REST API client and its integration tests in Kotlin Multiplatform]]></title>
            <link>https://medium.com/kotlin-academy/how-to-create-a-rest-api-client-and-its-integration-tests-in-kotlin-multiplatform-d76c9a1be348?source=rss-c3fe54d1497b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d76c9a1be348</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Jorge Sánchez (xurxodev)]]></dc:creator>
            <pubDate>Fri, 01 Mar 2019 09:43:26 GMT</pubDate>
            <atom:updated>2023-07-11T15:16:09.681Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZOoqp8Yxb0Vkc7k3FO9dA.png" /><figcaption>Kotlin Multiplatform Library</figcaption></figure><p>This article is an English translation from my original article in my blog <a href="http://xurxodev.com/cliente-api-rest-y-test-de-integracion-en-kotlin-multiplatform">xurxodev.com</a>.</p><p>Subscribe to my Spanish newsletter where I write stories about my vision of the software development: <a href="https://xurxodev.com/#/portal/signup">https://xurxodev.com/#/portal/signup</a></p><p>Most of the mobile applications are based on communication with an API Rest.</p><p>The integration with an external service is fundamental in mobile development. To have an optimal integration, it is necessary to ensure it by integration tests.</p><p>With the appearance of Kotlin Multiplatform, there is a very interesting scenario like having a client of a REST API in a multiplatform library and that we can use it from both an Android application and iOS application.</p><p>In this blog post, we will review how we can create a REST API client using Kotlin Multiplatform and how to create the integration tests needed to verify that our integration works correctly.</p><p>A few weeks ago I participated in a <a href="https://blog.karumi.com/5th-mobile-testing-training-edition-is-over/">mobile testing training of Karumi</a> where we made this <a href="https://medium.com/%20/%20/github.com/Karumi/KataTODOApiClientKotlin">kata</a>, we will review a Kotlin Multiplatform version.</p><h3>API REST</h3><p>The client that we are going to create communicates with the following web service: <a href="http://jsonplaceholder.typicode.com/">http://jsonplaceholder.typicode.com/</a></p><p>This REST API manages tasks, you will be able to get all the existing tasks, get a task using its identifier, add a new task, update a task or delete an existing task.</p><h3>Creating the Gradle project</h3><p>The first thing to do is to create the project, you can use Intellij or Android Studio.</p><p>The detail explanation of how to configure a Kotlin Multiplatform Library is out of the scope of this post but, here yo have the official documentation of Jetbrains: <a href="https://kotlinlang.org/docs/tutorials/multiplatform-library.html">Multiplatform Kotlin library</a>.</p><h3>Setting up the continuous integration</h3><p>The best time to set up CI for a project is at the beginning, so this would be the next step.</p><p>I’ve used Travis, all you have to do is going to <a href="https://travis-ci.org/">https://travis-ci.org</a>, enabling your Github project for continuous integration and adding a travis.yml file in the root directory of the project:</p><pre>os: osx<br>  osx_image: xcode10.1</pre><pre>script:<br>  - ./gradlew build</pre><p>In this file, we indicate OS X as the operating system where to perform the build.</p><p>This is necessary to execute the tests that we are going to create in an iOS emulator.</p><p>And finally, we indicate the script command to run the build task.</p><p>Among other subtasks, build task will compile the code of the library for the JVM, also for iOS and finally, It will run the tests on both platforms.</p><h3>Creating the client</h3><h4>Libraries to use</h4><p>We need the next libraries:</p><ul><li><a href="https://ktor.io/">Ktor</a>, it’s a multiplatform library to make requests to a remote service. It’s similar to Retrofit for Android or Alamofire and AFNetworking for iOS.</li><li><a href="https://github.com/Kotlin/kotlinx.serialization">Kotlinx Serialization</a>, it’s a multiplatform library to serialize and to deserialize, JSON is one of the supported formats.</li></ul><h4>TodoApiClient</h4><p>Our client contains a HttpClient to make requests and receive by constructor a HttpClientEngine, we will see why further on.</p><p>The engine can be assigned explicitly or implicitly by artifacts you have included in the build.gradle file.</p><p>There are some engines for JVM like Apache, Jetty, OkHttp; for iOS it only exists one iOS engine, it uses the asynchronous NSURLSession internally and it has no additional configuration.</p><pre>class TodoApiClient constructor(      <br>    httpClientEngine: HttpClientEngine? = null) { </pre><pre>    companion object {         <br>        const val BASE_ENDPOINT =  <br>              &quot;http://jsonplaceholder.typicode.com&quot;     <br>    }<br>      <br>    private val client: HttpClient = <br>         HttpClient(httpClientEngine!!) {             <br>             install(JsonFeature) {             <br>               serializer = KotlinxSerializer().apply {                  <br>                  register(Task.serializer())            <br>         } <br>    }   <br> }</pre><p>We are going to have a method for each of the actions that the remote service allows, let’s see some:</p><pre>suspend fun getAllTasks(): Either&lt;ApiError, List&lt;Task&gt;&gt; = try {<br>    val tasksJson = client.<em>get</em>&lt;String&gt;(&quot;$BASE_ENDPOINT/todos&quot;)<br><br>    // JsonFeature does not working currently with root-level array<br>    // https://github.com/Kotlin/kotlinx.serialization/issues/179<br>    val tasks = Json.nonstrict.parse(Task.serializer().<em>list</em>,   <br>                tasksJson)<br><br>    Either.Right(tasks)<br>} catch (e: Exception) {<br>    handleError(e)<br>}<br><br>suspend fun addTask(task: Task): Either&lt;ApiError, Task&gt; = try {<br>    val taskResponse = client.<em>post</em>&lt;Task&gt;(&quot;$BASE_ENDPOINT/todos&quot;) <strong>{<br>        </strong><em>contentType</em>(ContentType.Application.Json)<br>        body = task<br>    <strong>}<br><br>    </strong>Either.Right(taskResponse)<br>} catch (e: Exception) {<br>    handleError(e)<br>}</pre><p>Notice that every method returns an Either type, remember that it is a <a href="http://xurxodev.com/desde-donde-comunicar-o-tratar-errores-parte-2/">functional programming technique</a> to deal with errors without the use of exceptions.</p><p>In more traditional oriented object programming, each of these methods could return exceptions.</p><p>If the result is satisfactory, we return the right type of the corresponding generic.</p><p>In case of an error, Ktor returns an exception that we handle in its own method:</p><pre>private fun handleError(exception: Exception): Either&lt;ApiError, Nothing&gt; =<br>    if (exception is BadResponseStatusException) {<br>        if (exception.statusCode.value == 404) {<br>            Either.Left(ItemNotFoundError)<br>        } else {<br>            Either.Left(UnknownError(exception.statusCode.value))<br>        }<br>    } else {<br>        Either.Left(NetworkError)<br>    }</pre><h3>Integration tests</h3><p>To test the integration of our client with the Rest API, we need to verify the following:</p><ul><li>The requests are sent correctly to the API: endpoint, verb, headers, body if applicable.</li><li>The server responses are parsed correctly.</li><li>The server error responses are handled correctly.</li></ul><p>To perform these checks we have to simulate server responses and to be able to access in some way the HTTP requests that we have sent.</p><h4>Libraries to use</h4><p>We need the next libraries:</p><ul><li><a href="https://github.com/ktorio/ktor/tree/master/ktor-client/ktor-client-mock">ktor-client-mock</a>, it’s a multiplatform library that exposes MockEngine and allows us to simulate server responses and to access the sent requests to perform validations.</li><li><a href="https://github.com/Kotlin/kotlinx.coroutines">Kotlinx coroutines</a>, Ktor is based on <a href="https://kotlinlang.org/docs/reference/coroutines/composing-suspending-functions.html">suspending functions</a> and for this reason, we need the coroutines library to invoke our client from the tests.</li></ul><h4>Creating the tests</h4><p>Let’s see some tests that we can create.</p><p>The first tests we could try are to verify the todos endpoint, for example:</p><ul><li>Verify the response is parsed correctly.</li><li>Verify that accept header is sent.</li><li>Verify in case of an error that it is processed properly.</li></ul><p>What infrastructure do we need? We need to have a way to configure a MockEngine where we can simulate a response and pass this MockEgine to our client in the constructor instead of a real one.</p><p>We need a JSON that represents the server’s response, the simplest approach would be to have a function that returns the JSON string:</p><pre>fun getTasksResponse() =<br>    &quot;[{\n&quot; +<br>        &quot;  \&quot;userId\&quot;: 1,\n&quot; +<br>        &quot;  \&quot;id\&quot;: 1,\n&quot; +<br>        &quot;  \&quot;title\&quot;: \&quot;delectus aut autem\&quot;,\n&quot; +<br>        &quot;  \&quot;completed\&quot;: false\n&quot; +<br>        &quot;},&quot; +<br>        &quot; {\n&quot; +<br>        &quot;  \&quot;userId\&quot;: 1,\n&quot; +<br>        &quot;  \&quot;id\&quot;: 2,\n&quot; +<br>        &quot;  \&quot;title\&quot;: \&quot;quis ut nam facilis et officia qui\&quot;,\n&quot; +<br>        &quot;  \&quot;completed\&quot;: false\n&quot; +<br>        &quot;}, &quot; +<br>        &quot;{\n&quot; +<br>        &quot;  \&quot;userId\&quot;: 2,\n&quot; +<br>        &quot;  \&quot;id\&quot;: 3,\n&quot; +<br>        &quot;  \&quot;title\&quot;: \&quot;fugiat veniam minus\&quot;,\n&quot; +<br>        &quot;  \&quot;completed\&quot;: false\n&quot; +<br>        &quot;},&quot; +<br>        &quot;{\n&quot; +<br>        &quot;  \&quot;userId\&quot;: 2,\n&quot; +<br>        &quot;  \&quot;id\&quot;: 4,\n&quot; +<br>        &quot;  \&quot;title\&quot;: \&quot;et porro tempora\&quot;,\n&quot; +<br>        &quot;  \&quot;completed\&quot;: true\n&quot; +<br>        &quot;}]&quot;</pre><p>Now we need to be able to configure a Mock Engine to return stub responses and to use this one to access the sent request to realize validations about it.</p><p>We can create a base class for our tests or create a specific class to realize this work. I like to <a href="http://xurxodev.com/favoreciendo-la-composicion-sobre-la-herencia-tambien-en-los-test/">favour the composition over the inheritance also in the tests</a>.</p><pre>class TodoApiMockEngine {<br>    private lateinit var mockResponse: MockResponse<br>    private var lastRequest: MockHttpRequest? = null<br><br>    fun enqueueMockResponse(<br>        endpointSegment: String,<br>        responseBody: String,<br>        httpStatusCode: Int = 200<br>    ) {<br>        mockResponse = MockResponse(endpointSegment, responseBody, httpStatusCode)<br>    }<br><br>    fun get() = MockEngine <strong>{<br>        </strong>lastRequest = this<br><br>        when (url.encodedPath) {<br>            &quot;${mockResponse.endpointSegment}&quot; -&gt; {<br>                MockHttpResponse(<br>                    call,<br>                    HttpStatusCode.fromValue(<br>                    mockResponse.httpStatusCode),<br>                    <em>ByteReadChannel</em>(mockResponse.responseBody<br>                        .<em>toByteArray</em>(Charsets.UTF_8)),<br>                    <em>headersOf</em>(HttpHeaders.ContentType <em>to listOf</em>(<br>                    ContentType.Application.Json.toString()))<br>                )<br>            }<br>            else -&gt; {<br>                <em>error</em>(&quot;Unhandled ${url.<em>fullPath</em>}&quot;)<br>            }<br>        }<br>    <strong>}<br><br>    </strong>fun verifyRequestContainsHeader(key: String, <br>         expectedValue: String) {<br>        val value = lastRequest!!.headers[key]<br>        <em>assertEquals</em>(expectedValue, value)<br>    }<br><br>    fun verifyRequestBody(addTaskRequest: String) {<br>        val body = (lastRequest!!.content as TextContent).text<br><br>        <em>assertEquals</em>(addTaskRequest, body)<br>    }<br><br>    fun verifyGetRequest() {<br>        <em>assertEquals</em>(HttpMethod.Get.value,  <br>        lastRequest!!.method.value)<br>    }<br><br>    fun verifyPostRequest() {<br>        <em>assertEquals</em>(HttpMethod.Post.value,  <br>                     lastRequest!!.method.value)<br>    }<br><br>    fun verifyPutRequest() {<br>        <em>assertEquals</em>(HttpMethod.Put.value, <br>                     lastRequest!!.method.value)<br>    }<br><br>    fun verifyDeleteRequest() {<br>        <em>assertEquals</em>(HttpMethod.Delete.value, <br>                     lastRequest!!.method.value)<br>    }<br>}</pre><p>As you can see in this class, in the get function, we configure a MockEngine where depending on the encoded path, we will return a response with an HTTP status code and a body that it’s been passed in the enqueueMockResponse method.</p><p>If the encodedPath does not match, we throw an error:</p><pre>error(&quot;Unhandled ${url.fullPath}&quot;)</pre><p>In this way it is not necessary that we create a specific test for each endpoint that validates that the endpoint of the sent request is correct, it will be validated in each test implicitly.</p><p>And finally we write our tests:</p><pre>class TodoApiClientShould {<br>    companion object {<br>        private const val ALL_TASK_SEGMENT = &quot;/todos&quot;<br>    }<br><br>    private val todoApiMockEngine = TodoApiMockEngine()<br><br>    @Test<br>    fun `send accept header`() = <em>runTest </em><strong>{<br>        </strong>val apiClient = givenAMockTodoApiClient(<br>                    ALL_TASK_SEGMENT, <em>getTasksResponse</em>())<br><br>        apiClient.getAllTasks()<br><br>        todoApiMockEngine<br>         .verifyRequestContainsHeader(&quot;Accept&quot;, &quot;application/json&quot;)<br>    <strong>}<br><br>    </strong>@Test<br>    fun `send request with get http verb getting all task`() =   <br>      <em>runTest </em><strong>{<br>        </strong>val apiClient = givenAMockTodoApiClient(ALL_TASK_SEGMENT, <br>                        <em>getTasksResponse</em>())<br><br>        apiClient.getAllTasks()<br><br>        todoApiMockEngine.verifyGetRequest()<br>    <strong>}<br><br>    </strong>@Test<br>    fun `return tasks and parses it properly`() = <em>runTest </em><strong>{<br>        </strong>val apiClient = givenAMockTodoApiClient(ALL_TASK_SEGMENT, <br>                        <em>getTasksResponse</em>())<br><br>        val tasksResponse = apiClient.getAllTasks()<br><br>        tasksResponse.<em>fold</em>(<br>            <strong>{ </strong>left <strong>-&gt; </strong><em>fail</em>(&quot;Should return right but was left: <br>                           $left&quot;) <strong>}</strong>,<br>            <strong>{ </strong>right <strong>-&gt;<br>                </strong><em>assertEquals</em>(4, right.size.toLong())<br>                assertTaskContainsExpectedValues(right[0])<br>            <strong>}</strong>)<br>    <strong>}<br><br>    </strong>@Test<br>    fun `return http error 500 if server response internal server <br>         error getting all task`() =<br>        <em>runTest </em><strong>{<br>            </strong>val apiClient =givenAMockTodoApiClient(ALL_TASK_SEGMENT, <br>            httpStatusCode = 500)<br><br>            val tasksResponse = apiClient.getAllTasks()<br><br>            tasksResponse.<em>fold</em>(<br>                <strong>{ </strong>left <strong>-&gt; </strong><em>assertEquals</em>(UnknownError(500), left) <strong>}</strong>,<br>                <strong>{ </strong>right <strong>-&gt; </strong><em>fail</em>(&quot;Should return left but was right:  <br>                                $right&quot;) <strong>}</strong>)<br>        <strong>}</strong></pre><pre>    private fun assertTaskContainsExpectedValues(task: Task?) {<br>       <em>assertTrue</em>(task != null)<br>       <em>assertEquals</em>(task.id, 1)<br>       <em>assertEquals</em>(task.userId, 1)<br>       <em>assertEquals</em>(task.title, &quot;delectus aut autem&quot;)<br>       <em>assertFalse</em>(task.completed)<br>    }<br><br>    private fun givenAMockTodoApiClient(<br>       endpointSegment: String,<br>       responseBody: String = &quot;&quot;,<br>       httpStatusCode: Int = 200): TodoApiClient {<br>       <br>       todoApiMockEngine.enqueueMockResponse(endpointSegment,   <br>       responseBody, httpStatusCode)<br><br>       return TodoApiClient(todoApiMockEngine.get())<br>    }<br>}</pre><p>Notice that in the tests we return runTest, this is where the coroutines come into play.</p><p>The intention is to run the tests with runBlocking to execute the test synchronously.</p><p>As we are in the common module of a multiplatform project we do not have this builder available, so what we have to do is to create an abstraction and define its implementation within the source set of each platform following the <a href="http://xurxodev.com/kotlin-multiplatform-y-el-principio-de-inversion-de-dependencias/">expect/actual mechanism</a>:</p><pre>// This is within CommonTest source test     <br>internal expect fun &lt;T&gt; runTest(block: suspend () -&gt; T): T  </pre><pre>// This is within JvmTest source test     <br>internal actual fun &lt;T&gt; runTest(block: suspend () -&gt; T): T {            <br>    return runBlocking { block() }     <br>}</pre><pre>// This is within iosTest source test     <br>internal actual fun &lt;T&gt; runTest(block: suspend () -&gt; T): T {      <br>   return runBlocking { block() }<br>}</pre><h4>¿Why the tests are not executed for iOS?</h4><p>When you are running the build for the first time, the tests are not executed for iOS.</p><p>This is because the plugin by default only supports the execution of tests for macOS, Windows, etc.</p><p>But we can create a Gradle task that executes it easily.</p><pre>task iosTest {<br>    doLast {<br>        def binary = kotlin.targets.iOS.compilations.test.getBinary(&#39;EXECUTABLE&#39;, &#39;DEBUG&#39;)<br>        exec {<br>            commandLine &#39;xcrun&#39;, &#39;simctl&#39;, &#39;spawn&#39;, &quot;iPhone XR&quot;, binary.absolutePath<br>        }<br>    }<br>}<br>tasks.check.dependsOn iosTest</pre><h3>Kata and source code</h3><p>You can find the source code <a href="https://github.com/xurxodev/integration-testing-kotlin-multiplatform-kata">here</a>.</p><p>The master branch contains all the kata solved by me.</p><p>The best way to learn is by practising so I recommend using the integration-testing-kotlin-multiplatform-kata branch and you make the exercise by yourself.</p><h3>Related Course</h3><p><a href="http://xurxodev.com/curso-testing/">Testing Course</a></p><h3>Conclusions</h3><p>In this post, we have seen how to create a multiplatform library that contains a REST API client and also how to create tests that allow us to validate the integration with the remote service and run them over JVM and iOS emulator.</p><p>But this is just the example of a kata, it is not a library ready to release into production.</p><p><strong>Thanks for reading this article! If you liked it, press the 👏🏼 button so other people can read it too :)</strong></p><figure><a href="https://kotlin-academy.us17.list-manage.com/subscribe?u=5d3a48e1893758cb5be5c2919&amp;id=d2ba84960a"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XxZ6inD12UP7rnbt-2PJZw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d76c9a1be348" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kotlin-academy/how-to-create-a-rest-api-client-and-its-integration-tests-in-kotlin-multiplatform-d76c9a1be348">How to create a REST API client and its integration tests in Kotlin Multiplatform</a> was originally published in <a href="https://medium.com/kotlin-academy">kt.academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Commit Conf 2018]]></title>
            <link>https://medium.com/blog-de-kirei-studio/commit-conf-2018-541c1fa9878e?source=rss-c3fe54d1497b------2</link>
            <guid isPermaLink="false">https://medium.com/p/541c1fa9878e</guid>
            <category><![CDATA[eventos]]></category>
            <category><![CDATA[commit-conf]]></category>
            <category><![CDATA[events]]></category>
            <dc:creator><![CDATA[Jorge Sánchez (xurxodev)]]></dc:creator>
            <pubDate>Mon, 26 Nov 2018 06:05:33 GMT</pubDate>
            <atom:updated>2018-11-26T08:49:30.095Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xz-s8C2UpBJ7NHg1mhbyIg@2x.jpeg" /></figure><p>Los días 23 y 24 de Noviembre estuvimos en <a href="https://2018.commit-conf.com/">Commit Conf</a>, un evento nuevo organizado por el mismo equipo que hasta el año pasado organizaba Codemotion Madrid y se celebró en la Universidad San Pablo CEU, Boadilla del Monte.</p><p>Os dejo este <a href="https://blog.commit-conf.com/commit/">artículo </a>donde los organizadores explican el motivo de realizar este nuevo evento.</p><p>Lo único que cambia es el nombre pero el evento era prácticamente igual a los Codemotion Madrid de estos últimos años en cuanto a organización, lugar del evento, tipo de charlas, comida, número de asistentes, incluso las fechas coincidían.</p><h3>Charlas que más nos gustaron</h3><p>En este evento hay 12 tracks paralelos por lo tanto hay muchísimas charlas y talleres.</p><p>Voy a mencionar algunas de las que más nos gustaron, de las que asistimos, que lógicamente son las más alineadas con nuestras inquietudes y tecnologías que utilizamos.</p><h4>Unconference Testing: Tips &amp; Tricks de Joaquín Engelmo</h4><p>Como novedad en esta edición había un track dedicado a unconference en formato open space, estuvimos en el primero del viernes que trataba sobre testing.</p><p>En un Open Space no hay un ponente preestablecido que da una charla, hay diferentes formatos de open space, como charlas improvisadas o debates.</p><p>Debate fue el formato elegido por <a href="https://twitter.com/kinisoftware">Joaquín Engelmo</a>, encargado de dirigirlo.</p><p>Nos pusimos en círculo apartando las mesas y se creo un ambiente bastante cercano.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pc2-uvqApu0bQ9O16U74Ng@2x.jpeg" /></figure><p>Fue un experiencia nueva en este tipo de evento que me gustó, hubo bastante participación. Básicamente consistía en que Joaquín sacaba un tema relacionado sobre testing y luego quien quería iba contando anécdotas, consejos o problemas sobre ese tema en base a su experiencia.</p><p>En el debate había perfiles conocidos en la comunidad que ya suelen hablar de testing y buenas prácticas a través de sus blogs, canales de YouTube o redes sociales como <a href="https://twitter.com/raulvillaresbg">Raul Villares</a> de <a href="https://comunidadcode.com/">Comunidad Code</a> o <a href="https://twitter.com/JavierCane">Javier</a> y <a href="https://twitter.com/rafaoe">Rafa</a> de <a href="https://codely.tv/">CodelyTV</a>. Aportaron consejos en ciertos temas, pero el resto de personas que participó me dio la sensación de tener buena experiencia en testing, es algo que hace años no eran tan común.</p><h4>When Clean Architecture met to Kotlin: A Love Story de Nicolás Patarino</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FET1lrO8SkZo%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DET1lrO8SkZo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FET1lrO8SkZo%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/7fe90fbecc4fa2b7580070df8b590795/href">https://medium.com/media/7fe90fbecc4fa2b7580070df8b590795/href</a></iframe><p>Fue una charla donde el tema central era ver lo bien que se entienden Kotlin y Clean Architecture.</p><p>El formato de la charla era divertido porque estaba contado como una historia en una película donde había interpretes como JackeClean Stone, Javinson Ford y Ryan Kotlin.</p><p>En la charla Nicolás hace énfasis, contado de esta forma tan divertida, las ventajas de Kotlin frente a Java a la hora de utilizar Clean Architecture.</p><p>Una de estas ventajas que comentó Nicolas es la posibilidad de tener características clasicas de la programción funcional como <a href="https://blog.kirei.io/tipos-de-datos-algebraicos-sum-en-kotlin-y-swift-73f22bdec63">datos algebraicos de tipo sum</a> mediente sealed class y cómo nos puede ayudar a mejorar el modelado de nuestro dominio.</p><p>Esta claro que Kotlin ha encajado muy bien en la comunidad, nosotros hemos empezado hace tiempo a utilizarlo en nuestros proyectos y a escribir sobre ello en este blog.</p><p>Aprovecho para dejaros un enlace a nuestros <a href="https://blog.kirei.io/tagged/kotlin">artículos sobre Kotlin</a>.</p><p>Presentación: <a href="https://speakerdeck.com/npatarino/when-clean-architecture-met-kotlin-a-love-story-vol-2">When Clean Architecture met Kotlin: A love story</a>.</p><h4>El Testing en front end ya no es para gurús de Ricardo Borillo</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5xaDvCayGu4%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5xaDvCayGu4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5xaDvCayGu4%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/de74521f2a927f2d3a62045321e1c11c/href">https://medium.com/media/de74521f2a927f2d3a62045321e1c11c/href</a></iframe><p>En esta charla Ricardo no defraudó y cumplió con nuestras expectativas. Nos contó como poder hacer pruebas en la parte front end.</p><p>Hizo referencia a los siguientes olores a los que deberíamos prestar atención en nuestro código front end:</p><ul><li>Acoplamiento</li><li>Falta de niveles de abstracción</li><li>Falta de semántica</li></ul><p>Hizo un repaso a conceptos básicos de testing como principios FIRST.</p><p>Hizo incidencia también en la importancía de que los test tuvieran valor de negocio.</p><p>La charla avanzó mostrándonos código de una app hecha con React centrándose en dos puntos:</p><ul><li>Test de aceptación:</li></ul><p>En este punto enseñó test de aceptación utilizando el patrón Page Object y utilizando como framework <a href="https://www.cypress.io/">Cypress.io</a></p><ul><li>Test de integración/unitarios</li></ul><p>En este punto nos enseño test utilizando <a href="https://jestjs.io/">Jest</a> como framework y <a href="https://github.com/kentcdodds/react-testing-library">React Testing Library</a>, y comentando algunas de las herramientas que tenemos disponibles en este entorno como matches personalizados, mocks o Snapshot Testing.</p><p>Presentación: <a href="https://speakerdeck.com/borillo/el-testing-en-javascript-ya-no-es-para-gurus">El Testing en front end ya no es para gurús</a>.</p><h4>Dame tus tipo pegaso de Jorge Barroso</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FeCtczIdfeFE%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DeCtczIdfeFE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FeCtczIdfeFE%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/08a2828cadd43b4af020259f82936f35/href">https://medium.com/media/08a2828cadd43b4af020259f82936f35/href</a></iframe><p>Para el final quedó la charla de Jorge Barroso donde nos contó la importancia de los tipos para dar semántica al código.</p><p>Inició la charla tratando de desmontar algunos argumentos que se suelen dar en el sector para defender el uso o no uso de tipos y nos dejo una frase interesante:</p><blockquote>Los tipos no es sobre static o dynamic, es sobre la capacidad de modelar y añadir semántica a tu dominio.</blockquote><p>Continuó la charla enseñando código y dando algunos consejos, herramientas sobre como dar más semántica al código viendo ejemplos en lenguajes dinámicos como Javascript o Python y en lenguajes de tipado estático como Scala o Kotlin.</p><p>Uno de los consejos, una vez más en este evento, fue el uso de <a href="http://xurxodev.com/tipos-de-datos-algebraicos/">datos algebraicos de tipo sum</a> como por ejemplo en Kotlin mediante <a href="https://blog.kirei.io/tipos-de-datos-algebraicos-sum-en-kotlin-y-swift-73f22bdec63">sealed class</a>, en python mediante union o en javascript mediante la librería <a href="https://monet.github.io/monet.js/">Monet</a>.</p><p>Presentación: <a href="https://speakerdeck.com/karumi/dame-tus-tipos-pegaso-b11e71b1-60f3-431b-97e8-1b8b73f1bc73">Dame tus tipos pegaso</a>.</p><h3>Diversidad</h3><p>Uno de los puntos fuertes de este evento es la diversidad de charlas que hay, es muy difícil contentar a 2000 personas pero sea cual sea tu perfil seguro que hay charlas que te van a interesar.</p><p>En nuestro caso en concreto hemos echado en falta más charlas relacionadas con el mundo mobile, por poner un ejemplo, solo hubo una charla sobre Swift.</p><p>Sin embargo nos han resultado demasiadas las charlas sobre microservicios, Kubernetes etc.</p><h3>Conclusión</h3><p>Un fin de semana intenso donde aprender y relacionarse con gente del sector.</p><p>Me gustaría hacer una mención especial a la <a href="https://www.youtube.com/channel/UCd_1KHg4t2VKGsSDF8OD5Cw/videos"><strong>Commit Conf</strong></a> y a <a href="https://www.youtube.com/user/AutentiaMedia/videos"><strong>Autentia</strong></a> por grabar muchas de las charlas, incluso ofrecer algunas en ‘<em>streaming</em>’ por parte de Commit Conf.</p><p>También me gustaría destacar la rápida disponibilidad de las charlas en el canal de YouTube de <a href="https://www.youtube.com/channel/UCd_1KHg4t2VKGsSDF8OD5Cw/videos"><strong>Commit Conf</strong></a>.</p><p>Gracias a ambos.</p><p>Por cierto, <a href="https://www.koliseo.com/events/commit-2018/r4p/5630471824211968/agenda#/5116072650866688">aquí</a> os dejo la agenda donde aparecen slides y vídeos correspondientes.</p><p><strong>¡Gracias por leer este artículo! Si te ha gustado, pulsa el botón </strong>👏🏼 <strong>para que otras personas puedan leerlo también :)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=541c1fa9878e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blog-de-kirei-studio/commit-conf-2018-541c1fa9878e">Commit Conf 2018</a> was originally published in <a href="https://medium.com/blog-de-kirei-studio">Blog de Kirei Studio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tipos de Datos Algebraicos Sum en Kotlin y Swift]]></title>
            <link>https://medium.com/blog-de-kirei-studio/tipos-de-datos-algebraicos-sum-en-kotlin-y-swift-73f22bdec63?source=rss-c3fe54d1497b------2</link>
            <guid isPermaLink="false">https://medium.com/p/73f22bdec63</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Jorge Sánchez (xurxodev)]]></dc:creator>
            <pubDate>Mon, 15 Oct 2018 10:21:28 GMT</pubDate>
            <atom:updated>2018-10-15T10:21:28.467Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cG4LSBr2ZGSCmpNfl-Mxmw.png" /></figure><p>Los tipos de datos algebraicos es un concepto muy relacionado con la programación funcional.</p><p>En mi blog <a href="http://xurxodev.com/tipos-de-datos-algebraicos/">xurxodev.com</a> tengo una introducción a los tipos de datos algebraicos, que te animo a leer previamente si no estas familiarizado con estos conceptos.</p><p>Tanto Kotlin como Swift tienen soporte directo para diseñar tipos sum, vamos a ver en este artículo como se hace en cada lenguaje.</p><h3>Kotlin</h3><p>Kotlin nos proporciona dos mecanismos para representar un tipo con un set de valores restringidos: Enum y Sealed Class.</p><h4>Enum</h4><p>Los enumerados ya existían en Java, en Kotlin son iguales.</p><p>La forma más básica de enumerado es así:</p><pre>enum class OrderStatus {<br>     APPROVED, <br>     REJECTED<br>}</pre><p>Cada posible constante de un enumerado es un objeto, como son instancias de enum class, podríamos definir un enumerado donde además cada opción posible del set contenga estado:</p><pre><strong>enum class</strong> DayOfWeek(<strong>val</strong> dayNumber: Int) {<br>  MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4),<br>  FRIDAY(5), SATURDAY(6), SUNDAY(7)<br>}</pre><p>Pero los enumerados tienen limitaciones que hacen inviable ser utilizados como Sum Types:</p><ul><li>De cada opción del enumerado solo puede existir una instancia.</li><li>Todas las opciones del set, al ser instancias de enum class, deben tener el mismo estado. Esto quiere decir que no puedo tener estados distintos en cada opción del set. Si necesito añadir una propiedad en un caso, todas las opciones tendrán esa propiedad aunque no la necesiten.</li></ul><h4>Sealed Class</h4><p>Las clases selladas si han sido diseñadas para poder representar tipos sum, al igual que ocurre con sealed trait en Scala por ejemplo.</p><p>Recordad que un tipo sum se compone de una serie de subtipos donde el valor final del tipo solo puede ser uno de los subtipos definidos.</p><p>El caso más sencillo de tipo sum que existe en todos los lenguajes es el tipo boolean donde solo puede ser true o false.</p><p>En lenguajes tradicionales orientados a objetos como Java o C# no se incorpora soporte directo para diseñar tipos sum.</p><p>En cierto modo, las sealed class, se pueden ver como una evolución de los enumerados.</p><p>Podemos representar los mismos escenarios de antes con enum mediante sealed class:</p><p>Veamos el ejemplo básico de antes:</p><pre><strong>sealed class </strong>OrderStatus {<br>    <strong>object </strong>Approved: OrderStatus()<br>    <strong>object </strong>Rejected: OrderStatus()<br>}</pre><p>Hay varias cosas a destacar:</p><ul><li>Cada opción debe de heredar de la clase sellada</li><li>He especificado que cada opción es un object, lo que en Kotlin quiere decir que cada opción será un singleton y por lo tanto solo existirá una instancia de cada una, al igual que ocurre con los enumerados.</li></ul><p>Así se utilizaría:</p><pre><strong>val approvedStatus </strong>= OrderStatus.Approved<br><strong>val rejectedStatus </strong>= OrderStatus.Rejected</pre><p>También podemos almacenar el mismo tipo estado en todas las opciones, creando esa propiedad en la clase base y asignando su valor vía constructor:</p><pre><strong>sealed class </strong>DayOfWeek(<strong>val dayNumber</strong>: Int) {<br>    <strong>object </strong>Monday: DayOfWeek(1)<br>    <strong>object </strong>Tuesday: DayOfWeek(2)<br>    <strong>object </strong>Wednesday: DayOfWeek(3)<br>    <strong>object </strong>Thursday: DayOfWeek(4)<br>    <strong>object </strong>Friday: DayOfWeek(5)<br>    <strong>object </strong>Saturday: DayOfWeek(6)<br>    <strong>object </strong>Sunday: DayOfWeek(7)<br>}</pre><p>Así se utilizaría:</p><pre><strong>val monday </strong>= DayOfWeek.Monday<br><br><strong>val dayNumber </strong>= <strong>monday</strong>.<strong>dayNumber</strong></pre><p>Pero las limitaciones que tienen los enum, se resuelven con Sealed class:</p><ul><li>Se puede definir la posibilidad de crear más de una instancia para una de las opciones cambiando la definición de object por class.</li><li>En caso de tener una opción como class, entonces se le puede añadir un constructor específico a esa opción, de este modo, tenemos la posibilidad de tener estados independientes entre las opciones.</li></ul><pre><strong>sealed class </strong>OrderStatus {<br>    <strong>object </strong>Approved: OrderStatus()<br>    <strong>class </strong>Rejected(<strong>val reason</strong>: String): OrderStatus()<br>}</pre><p>Así se utilizaría:</p><pre><strong>val approvedStatus </strong>= OrderStatus.Approved<br><strong>val rejectedStatus </strong>= OrderStatus.Rejected (reason = <strong>&quot;reason message&quot;</strong>)</pre><h4>Aprovechando la ventaja del compilador</h4><p>Una de las ventajas de utilizar tipos sum es que al componerse de un set de restringido de posibles opciones, en aquellas partes de nuestro código donde estemos utilizando expresiones tipo match, la compilación fallará en caso de que no sea exhaustiva, es decir, falte alguna rama por definir y no tenga puesta la rama else.</p><p>Vamos a ver como se hace en Kotlin:</p><p>Para definir expresiones match existe when.</p><pre><strong>private fun </strong>getOrderNotification(orderStatus:OrderStatus): String{<br>    <strong>return when</strong>(orderStatus) {<br>        <strong>is </strong>OrderStatus.Approved -&gt; <strong>&quot;The order has been approved&quot;<br>        is </strong>OrderStatus.Rejected -&gt; <strong>&quot;The order has been rejected.&quot;       <br>                                  + &quot;reason:&quot; </strong>+ orderStatus.<strong>reason<br>    </strong>}<br>}</pre><p>Hay varias cosas a tener en cuenta:</p><ul><li>En Kotlin when realiza smartcast, lo que quiere decir que en este ejemplo no es necesario que realicemos la conversión de OrderStatus a OrderStatus.Rejected para acceder a la propiedad reason.</li><li>Si no hubieramos definido qué hacer para el caso rejected, fallaría la compilación y en el IDE nos aparece un aviso como este:</li></ul><p><strong>‘when’ expression must be exhaustive, add necessary ‘is Rejected’ branch or ‘else’ branch instead.</strong></p><pre><strong>private fun </strong>getOrderNotification(orderStatus:OrderStatus): String{<br>    <strong>return when</strong>(orderStatus) {<br>        <strong>is </strong>OrderStatus.Approved -&gt; <strong>&quot;The order has been approved&quot;<br>    </strong>}<br>}<br></pre><ul><li>when puede ser utilizando como una expresión o como una declaración. Si es usado como una expresión, el valor de la rama seleccionada se convierte en el valor de la expresión general. Si se usa como una declaración, los valores de las ramas individuales se ignoran. Esto quiere decir que <strong>el error de compilación en caso de faltarnos alguna rama solo se produce cuando when es utilizado como una expresión</strong>, utilizando el resultado.</li></ul><h3>Swift</h3><p>Swift nos proporciona solo un mecanismo de representar un tipo con un set de valores restringidos: Enum.</p><p>Pero al contrario de lo que sucede en Kotlin, en Swift los enumerados si se pueden utilizar para representar tipos sum, ya que no tienen las limitaciones que si existen en Kotlin.</p><p>Se pueden utilizar para los ejemplos más sencillos como ocurre con los enum de Kotlin.</p><pre>enum OrderStatus {<br>   case approved<br>   case rejected<br>}</pre><p>Así se utilizaría:</p><pre>let approvedStatus = OrderStatus.approved<br>let rejectedStatus = OrderStatus.rejected</pre><p>En Swift el concepto de tener estado para las opciones del enumerado se conoce como valores asociados.</p><p>Para resolver el mismo ejemplo para DayOfWeek que antes, donde solo teníamos un valor asociado y de forma consecutiva, podemos utilizar lo que la documentación de Swift llama valores implícitamente asignados:</p><pre>enum DayOfWeek: Int {<br>   case monday = 1,tuesday, wednesday, thursday, friday, saturday,     <br>        sunday<br>}</pre><p>Solo hace falta asignar el primero y el resto los asigna Swift automáticamente.</p><p>Así se utilizaría:</p><pre>let dayOfWeek = DayOfWeek.tuesday.rawValue</pre><p>Pero los Enum en Swift incorporan características para utilizarlos como tipos sum:</p><ul><li>Existe más de una instancia para las opciones del enumerado</li><li>Cada opción del enumerado puede tener un inicializador específico consiguiendo tener valores asociados independientes entre las opciones</li></ul><pre>enum OrderStatus {<br>    case approved<br>    case rejected (String)<br>}</pre><p>Así se utilizaría:</p><pre>let approvedStatus = OrderStatus.approved<br>let rejectedStatus = OrderStatus.rejected(&quot;reason message&quot;)</pre><h4>Aprovechando la ventaja del compilador</h4><p>Al igual que sucedía en Kotlin, una de las ventajas de utilizar tipos sum es que al componerse de un set de restringido de posibles opciones, en aquellas partes de nuestro código donde estemos utilizando expresiones tipo match, la compilación fallará en caso de que no sea exhaustiva, es decir, falte alguna rama por definir.</p><p>Vamos a ver como se hace en Swift:</p><p>Para definir expresiones match existe switch.</p><pre>func getOrderNotification(orderStatus:OrderStatus) -&gt; String{<br>     switch orderStatus {<br>        case .approved: return &quot;The order has been approved&quot;<br>        case .rejected(let reason): return &quot;The order has been <br>                         rejected.&quot; + &quot;reason:&quot; + reason<br>     }<br>}</pre><p>Hay varias cosas a tener en cuenta también:</p><ul><li>En Swift los valores asociados al subtipo debe ser extraídos como parte de la declaración del switch especificando let o var.</li><li>Si no hubiéramos definido qué hacer para el caso rejected, fallaría la compilación y en el IDE nos aparece un aviso como este:</li></ul><p><strong>‘Switch must be exhaustive’.</strong></p><pre>func getOrderNotification(orderStatus:OrderStatus) -&gt; String{<br>     switch orderStatus {<br>        case .approved: return &quot;The order has been approved&quot;<br>     }<br>}</pre><h3>Conclusiones</h3><p>En este artículo hemos visto como podemos definir tipos algebraicos sum en Kotlin y Swift:</p><p>En Kotlin mediante sealed class y en Swift mediante enum podemos definir tipos sum.</p><p>En ambos lenguajes podemos sacar ventaja del compilador para hacer un código más seguro cuando utilizamos expresiones tipo match. En Kotlin tenemos when y en Swift switch para realizar estas expresiones.</p><p><strong>¡Gracias por leer este artículo! Si te ha gustado, pulsa el botón </strong>👏🏼 <strong>para que otras personas puedan leerlo también :)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73f22bdec63" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blog-de-kirei-studio/tipos-de-datos-algebraicos-sum-en-kotlin-y-swift-73f22bdec63">Tipos de Datos Algebraicos Sum en Kotlin y Swift</a> was originally published in <a href="https://medium.com/blog-de-kirei-studio">Blog de Kirei Studio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Alternativas a los callbacks de Java en Kotlin]]></title>
            <link>https://medium.com/blog-de-kirei-studio/alternativas-a-los-callbacks-de-java-en-kotlin-abc1c68f8cf7?source=rss-c3fe54d1497b------2</link>
            <guid isPermaLink="false">https://medium.com/p/abc1c68f8cf7</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Jorge Sánchez (xurxodev)]]></dc:creator>
            <pubDate>Mon, 03 Sep 2018 04:23:41 GMT</pubDate>
            <atom:updated>2018-09-03T04:23:41.164Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3bfqwSDmJIYmGMRJ7pBZjQ.png" /><figcaption>Alternativas a los callbacks de Java en Kotlin</figcaption></figure><p>Cuando trabajamos con Java de forma asíncrona, el uso de callbacks es la forma habitual para comunicar entre los distintos hilos las respuestas de lo que esta ocurriendo en un proceso.</p><p>Gracias a las características de Kotlin se abre un mundo nuevo de posibilidades que nos van a ayudar a realizar estas tareas de una forma más simple y legible.</p><h3>Callbacks en Java</h3><p>Cuando utilizamos Clean Architecture en Java y queremos obtener una lista de datos de la capa de datos, lo normal es que esa acción se haga de forma asíncrona utilizando un <a href="https://en.wikipedia.org/wiki/Thread_pool">Thread pool</a>, una librería como <a href="https://github.com/yigit/android-priority-jobqueue">Priority Job Queue</a><strong> </strong>o algo similar desde el presenter o el caso de uso. Entonces cuando termina el acceso a la capa de datos lo habitual, sin entrar en Observables de RxJava etc.., es utilizar callbacks para devolver la respuesta fallida o satisfactoria en el hilo de UI.</p><p>Los callbacks se crean definiendo un interface previamente, con los métodos que va a contener.</p><p>Veamos un ejemplo de como seria:</p><pre><strong>public class </strong>GetMovieByIdUseCase <strong>implements </strong>UseCase {<br><br>    <strong>public interface </strong>Callback {<br>        <strong>void </strong>onMovieDetailLoaded(<strong>final </strong>Movie movie);<br><br>        <strong>void </strong>onMovieNotFound();<br><br>        <strong>void </strong>onConnectionError();<br>    }<br><br>    <strong>private </strong>MovieRepository <strong>movieRepository</strong>;<br>    <strong>private </strong>Executor <strong>executor</strong>;<br>    <strong>private </strong>MainThread <strong>mainThread</strong>;<br>    <strong>private </strong>Callback <strong>callback</strong>;<br>    <strong>private </strong>Long <strong>movieId</strong>;<br><br>    <strong>public </strong>GetMovieUseCase(MovieRepository movieRepository,<br>            Executor executor,<br>            MainThread mainThread) {<br>        <strong>this</strong>.<strong>movieRepository </strong>= movieRepository;<br>        <strong>this</strong>.<strong>executor </strong>= executor;<br>        <strong>this</strong>.<strong>mainThread </strong>= mainThread;<br>    }<br><br>    <strong>public void </strong>execute(Long movieId, Callback callback) {<br>        <strong>this</strong>.<strong>movieId </strong>= <strong>movieId</strong>;<br>        <strong>this</strong>.<strong>callback </strong>= callback;<br>        <strong>this</strong>.<strong>executor</strong>.run(<strong>this</strong>);<br>    }<br><br>    @Override<br>    <strong>public void </strong>run() {<br>        <strong>try </strong>{<br>            Movie movie = <strong>movieRepository</strong>.getById(<strong>this</strong>.<strong>movieId</strong>);<br>            notifyMovieLoaded(movie);<br>        } <strong>catch </strong>(MovieNotFoundException e) {<br>            notifyMovieNotFoundError();<br>        } <strong>catch </strong>(Exception e) {<br>            notifyError();<br>        }<br>    }<br><br>    <strong>private void </strong>notifyError() {<br>        <strong>mainThread</strong>.post(<strong>new </strong>Runnable() {<br>            @Override<br>            <strong>public void </strong>run() {<br>                <strong>callback</strong>.onConnectionError();<br>            }<br>        });<br>    }<br><br>    <strong>private void </strong>notifyMovieLoaded(<strong>final </strong>Movie movie) {<br>        <strong>mainThread</strong>.post(<strong>new </strong>Runnable() {<br>            @Override<br>            <strong>public void </strong>run() {<br>                <strong>callback</strong>.onMovieDetailLoaded(movie);<br>            }<br>        });<br>    }<br><br>    <strong>private void </strong>notifyMovieNotFoundError() {<br>        <strong>mainThread</strong>.post(<strong>new </strong>Runnable() {<br>            @Override<br>            <strong>public void </strong>run() {<br>                <strong>callback</strong>.onMovieNotFound();<br>            }<br>        });<br>    }<br>}</pre><h4>Problemas de los callbacks</h4><p>El uso de callbacks tiene algunos problemas:</p><ul><li>El código queda más sucio.</li><li>Es más complejo de depurar.</li><li>Es menos legible sobre todo si existen varias llamadas asíncronas anidadas por el denominado callback hell.</li></ul><h3>Callbacks en Kotlin</h3><p>En Kotlin también es posible utilizar callbacks.</p><pre><strong>class </strong>GetMovieByIdUseCase(<strong>private val movieRepository</strong>: MovieRepository, <strong>private val executor</strong>: Executor, <strong>private val mainThread</strong>: MainThread) : UseCase {<br>    <strong><br>    interface </strong>Callback {<br>        <strong>fun </strong>onMovieDetailLoaded(movie: Movie)<br><br>        <strong>fun </strong>onMovieNotFound()<br><br>        <strong>fun </strong>onConnectionError()<br>    }<br>    </pre><pre><strong>    private var callback</strong>: Callback? = <strong>null<br>    private var movieId</strong>: Long? = <strong>null</strong></pre><pre>    <strong>fun </strong>execute(movieId: Long?, callback: Callback) {<br>        <strong>this</strong>.<strong>movieId </strong>= movieId<br>        <strong>this</strong>.<strong>callback </strong>= callback<br>        <strong>this</strong>.<strong>executor</strong>.run(<strong>this</strong>)<br>    }<br><br>    <strong>fun </strong>run() {<br>        <strong>try </strong>{<br>            <strong>val </strong>movie = <strong>movieRepository</strong>.getById(<strong>this</strong>.<strong>movieId</strong>!!)<br>            notifyMovieLoaded(movie)<br>        } <strong>catch </strong>(e: MovieNotFoundException) {<br>            notifyMovieNotFoundError()<br>        } <strong>catch </strong>(e: Exception) {<br>            notifyError()<br>        }<br><br>    }<br><br>    <strong>private fun </strong>notifyError() {<br>        <strong>mainThread</strong>.post(<em>Runnable </em><strong>{ callback</strong>!!.onConnectionError() <strong>}</strong>)<br>    }<br><br>    <strong>private fun </strong>notifyMovieLoaded(movie: Movie) {<br>        <strong>mainThread</strong>.post(<em>Runnable </em><strong>{ callback</strong>!!.onMovieDetailLoaded(movie) <strong>}</strong>)<br>    }<br><br>    <strong>private fun </strong>notifyMovieNotFoundError() {<br>        <strong>mainThread</strong>.post(<em>Runnable </em><strong>{ callback</strong>!!.onMovieNotFound() <strong>}</strong>)<br>    }<br>}</pre><p>Pero con las características que trae Kotlin existen opciones muy interesantes con las que se gana legibilidad y se puede optimizar mejor el código.</p><h3>Usando funciones en Kotlin</h3><p>En Kotlin para realizar tareas asíncronamente existen las <a href="https://kotlinlang.org/docs/reference/coroutines.html">co-rutinas</a> que nos van a ayudar a ejecutar código asíncrono pero escribiéndolo como si fuera síncrono.</p><p>Recordad que esta en fase experimental así hay que tener cuidado para <a href="https://blog.kirei.io/desacoplandonos-del-uso-de-co-rutinas-en-kotlin-4d229dfafa57">no acoplaros a ellas</a>. A mi me gusta crear un executor, con funciones para ejecutar asíncronamente o en el hilo de interfaz, que me abstraiga de uso de co-rutinas.</p><p>Las co-rutinas son funciones, en Kotlin las funciones son ciudadanos de primer orden y eso quiere decir que podemos almacenar funciones dentro de una variable.</p><p>También es posible definir <strong>funciones de orden superior</strong>, que son aquellas que tienen argumentos que a su vez son también una función o incluso devolven una función como resultado .</p><p>Veamos como sería el mismo ejemplo escrito en kotlin, utilizando co-rutinas y convirtiendo el método execute en una función de orden superior, donde reciba como argumentos las funciones a invocar cuando finaliza la llamada a la capa de datos, sin necesidad de definir un callback y ejecutar estas a través de co-rutinas.</p><p>Gracias al uso de funciones como parámetro, la ejecución de tareas utilizando co-rutinas podemos encapsularlo en la clase base, nos quedaría un código mucho más simple en cada caso de uso.</p><pre><strong>abstract class </strong>UseCase (<strong>private val executor</strong>: Executor){<br><br>    <strong>fun </strong>uiExecute(uiFun:<strong>suspend </strong>()-&gt;Unit){<br>        <strong>executor</strong>.uiExecute<strong>{</strong>uiFun()<strong>}<br>    </strong>}<br>    <strong>fun </strong>asyncExecute(asyncFun:<strong>suspend</strong>()-&gt;Unit){<br>        <strong>executor</strong>.asyncExecute <strong>{</strong>asyncFun()<strong>}<br>    </strong>}<br><br>}<br><strong>class </strong>GetMovieByIdUseCase (<strong>private val movieRepository</strong>: MovieRepository, <strong>private val executor</strong>: Executor): UseCase(executor) {<br>    <strong>fun </strong>execute(id: Long, onMovieLoaded: (Movie) -&gt; Unit, onMovieNotFoundError: () -&gt; Unit, onConnectionError: () -&gt; Unit) {<br>        asyncExecute <strong>{<br>            try </strong>{<br>                <strong>val </strong>movie = <strong>movieRepository</strong>.getById(id)<br><br>                uiExecute <strong>{</strong>onMovieLoaded(movie)<strong>}<br>            </strong>} <strong>catch </strong>(ex: MovieNotFoundException) {<br>                uiExecute <strong>{</strong>onMovieNotFoundError()<strong>}<br>            </strong>} <strong>catch </strong>(ex: Exception) {<br>                uiExecute <strong>{</strong>onConnectionError()<strong>}<br>            </strong>}<br>        <strong>}<br>    </strong>}<br>}</pre><h4>Ventajas</h4><ul><li>Poder pasar funciones como argumentos y el uso de lambdas o funciones anónimas desde el cliente del caso de uso nos ayuda a tener un código más simple.</li><li>No es necesario crear un interface previamente.</li><li>El uso de funciones nos permite llevarnos la lógica de invocar el executor a la clase base.</li></ul><h4>Desventajas</h4><ul><li>Con esta solución con cada nueva situación de error tenemos que añadir un argumento nuevo en el método execute.</li><li>Si el cliente del caso de uso, como puede ser un presenter, necesita invocar más casos de uso y necesita esperar a que todos terminen, seguimos teniendo un código que se lee mal con llamadas anidadas, en este caso desde el presenter.</li></ul><h3>Utilizando programación funcional</h3><p>En el apartado anterior hemos utilizado funciones como argumento pero eso no quiere decir que estemos utilizando programación funcional.</p><p>Kotlin, aun siendo un lenguaje orientado a objetos abre la puerta a la programación funcional. Hay un librería para Kotlin llamada <a href="https://arrow-kt.io/">Arrow</a> que intenta cubrir las carencias de Kotlin en programación funcional añadiendo tipos y abstracciones como Option (también se conoce como Maybe), Try, Either, IO, Functor, Applicative, Monad y otras características.</p><p>De todas formas sin llegar a utilizar una librería como <a href="https://arrow-kt.io/">Arrow</a>, es posible refactorizar un poco el código para orientarlo un poco a una programación más estilo funcional.</p><p>No creo que tengamos que decidir si realizamos programación orientada a objetos o funcional, creo que se pueden combinar según las necesidades de cada momento y el conocimiento del equipo.</p><p>No es necesario conocer en profundidad toda la teoría matemática que hay detrás de la programación funcional para aplicar pequeños tintes cuando nos interese si lo entendemos y eso mejora nuestro código.</p><h3>Funciones Puras</h3><p>En programación funcional se utilizan funciones puras, son aquellas que cumplen con dos requisitos básicos:</p><ul><li>Dado unos parámetros de entrada, la función siempre devolverá el mismo resultado para los mismos valores pasados como argumentos.</li><li>La función no debería ejecutar ningún efecto de lado.</li></ul><p>Efectos de lado son:</p><ul><li>Re-asignar una variable</li><li>Modificar una estructura de datos</li><li>Asignar un valor a un campo objeto</li><li>Lanzar una excepción, imprimir en la consola, leer o escribir en un fichero</li><li>Dibujar en la pantalla</li></ul><p>En nuestro ejemplo utilizábamos excepciones, que se lanzaban desde el repositorio. Según que escenarios, su uso pueden ser muy costoso o una mala práctica si las utilizamos para controlar el flujo de ejecución por ejemplo. Vamos a ver como podemos refactorizar el ejemplo utilizando conceptos funcionales sin utilizar excepciones.</p><h3>Either</h3><p>Es una mónada que representa un valor de uno de dos tipos posibles (es una unión disjunta).</p><p>Una instancia de Either es una instancia de Left o Right. Un uso común, aunque no exclusivo, de Either es para la gestión de errores.</p><p>Por convención Left se usa para el caso de error y Right se usa para el éxito.</p><p>En lenguajes exclusivamente funcionales o donde se puede realizar programación funcional pura este tipo viene de serie, como sucede en <a href="https://www.scala-lang.org/api/2.9.3/scala/Either.html">Scala</a> o <a href="http://hackage.haskell.org/package/base-4.11.1.0/docs/Data-Either.html">Haskell</a>.</p><p>Un implementación simple, escrita en Kotlin, pero suficiente para nuestro ejemplo podría ser la siguiente:</p><pre><strong>sealed class </strong>Either&lt;<strong>out </strong>L, <strong>out </strong>R&gt; {<br>    <em>//Failure<br>    </em><strong>data class </strong>Left&lt;<strong>out </strong>L&gt;(<strong>val value</strong>: L) : Either&lt;L, Nothing&gt;()<br><br>    <em>//Success<br>    </em><strong>data class </strong>Right&lt;<strong>out </strong>R&gt;(<strong>val value</strong>: R) : Either&lt;Nothing, R&gt;()<br><br>    <strong>val isRight get</strong>() = <strong>this is </strong>Right&lt;R&gt;<br>    <strong>val isLeft get</strong>() = <strong>this is </strong>Left&lt;L&gt;<br><br>    <strong>fun </strong>&lt;L&gt; left(a: L) = Left(a)<br>    <strong>fun </strong>&lt;R&gt; right(b: R) = Right(b)<br>}<br><br> <strong>fun </strong>&lt;L, R, T&gt; Either&lt;L, R&gt;.fold(left: (L) -&gt; T, right: (R) -&gt; T): T     <br>         =<br>        <strong>when </strong>(<strong>this</strong>) {<br>            <strong>is </strong>Either.Left  -&gt; left(value)<br>            <strong>is </strong>Either.Right -&gt; right(<strong>value</strong>)<br>        }<br> <strong>fun </strong>&lt;L, R, T&gt; Either&lt;L, R&gt;.flatMap(f: (R) -&gt; Either&lt;L, T&gt;): <br>        Either&lt;L, T&gt; =<br>        <em>fold</em>(<strong>{ this as </strong>Either.Left <strong>}</strong>, f)<br><br> <strong>fun </strong>&lt;L, R, T&gt; Either&lt;L, R&gt;.map(f: (R) -&gt; T): Either&lt;L, T&gt; =<br>        <em>flatMap </em><strong>{ </strong>Either.Right(f(<strong>it</strong>)) <strong>}</strong></pre><h3>Usando Either</h3><p>Tendríamos que definir en el dominio previamante los tipos de fallo que se pueden devolver en caso de error. Para ello utilizamos el concepto de <a href="https://kotlinlang.org/docs/reference/sealed-classes.html">sealed class</a> que existe en Kotlin.</p><p>Si necesitáramos más información en cada uno de los errores podríamos convertirlos en <a href="https://kotlinlang.org/docs/reference/data-classes.html">data classes</a> para que recibieran esa información por el constructor.</p><pre><strong>sealed class </strong>GetMovieFailure{<br>    <strong>class </strong>NetworkConnection: GetMovieFailure()<br>    <strong>class </strong>MovieNotFound: GetMovieFailure()<br>}</pre><p>El repositorio debería devolver un tipo Either, donde en caso de error devolvería un tipo de GetMovieFailure como Left o el Movie resultante como Right:</p><pre><strong>class </strong>FakeMovieRepository (<strong>val context</strong>: Application): MovieRepository {<br><br>    <strong>override fun </strong>getAll (): Either&lt;GetMoviesFailure,List&lt;Movie&gt;&gt; {<br>       ...<br>    }<br><br>   <strong>override fun </strong>getById (id: Long): Either&lt;GetMovieFailure,Movie&gt; {<br>      <strong>return </strong>getAll().<em>fold</em>(<br>      <strong>{<br>         </strong>Either.Left(GetMovieFailure.NetworkConnection())<br>      <strong>}</strong>,<br>      <strong>{<br>        if </strong>(<strong>it</strong>.<em>any </em><strong>{ </strong>movie <strong>-&gt; </strong>movie.<strong>id </strong>== id <strong>}</strong>){<br>            Either.Right(<strong>it</strong>.<em>first</em><strong>{it</strong>.<strong>id </strong>== id<strong>}</strong>)<br>        } <strong>else </strong>{<br>            Either.Left(GetMovieFailure.MovieNotFound())<br>        }<br>     <strong>}</strong>)<br>  }</pre><pre>    ...<br>}</pre><p>Al devolver un tipo Either que cubre todas las posibles situaciones, también en el caso de uso se invoca una única función para notificar el resultado. Esta función es recibida en el método execute y se pasa el resultado de tipo Either que devuelve el repositorio.</p><pre><strong>class </strong>GetMovieByIdUseCase(<strong>private val movieRepository</strong>: MovieRepository, <strong>private val executor</strong>: Executor) : UseCase(executor) {<br>    <strong>private var id</strong>: Long = 0<br><br>    <strong>fun </strong>execute(id: Long, onResult: (Either&lt;GetMovieFailure, Movie&gt;) -&gt; Unit) {<br>        <strong>this</strong>.<strong>id </strong>= id<br><br>        asyncExecute <strong>{<br>            val </strong>movieResult = <strong>movieRepository</strong>.getById(id)<br><br>            uiExecute <strong>{ </strong>onResult(movieResult) <strong>}<br>        }<br>    </strong>}<br>}</pre><p>Y posteriormente en el presenter se tomarian las decisiones de que hacer en cada situación.</p><pre><strong>class </strong>MoviePresenter(<strong>private val getMovieByIdUseCase</strong>: GetMovieByIdUseCase) {<br><br>    ...<br><br>    <strong>private fun </strong>loadMovie(id: Long) {<br>        loadingMovie()<br><br>        <strong>getMovieByIdUseCase</strong>.execute(id,<br>                onResult = <strong>{ </strong>result <strong>-&gt;<br>                    </strong>result.<em>fold</em>(<strong>{</strong>failure <strong>-&gt; </strong>showError(failure)<strong>}</strong>,   <br>                                <strong>{</strong>movie <strong>-&gt; </strong>showMovie(movie)<strong>}</strong>)<br>                <strong>}</strong>)<br>    }<br><br>    <strong>private fun </strong>showError(failure: GetMovieFailure) {<br>        <strong>when</strong>(failure){<br>           <strong>is </strong>GetMovieFailure.NetworkConnection -&gt;  <br>              showConnectionError()<br>           <strong>is </strong>GetMovieFailure.MovieNotFound -&gt;  <br>              showMovieNotFoundError()<br>        }<br>    }</pre><pre>    <strong>private fun </strong>showMovie(movie: Movie) {<br>        <strong>view</strong>?.hideLoading()<br>        <strong>view</strong>?.showMovie(movie)<br>    }<br><br>    <strong>private fun </strong>showMovieNotFoundError() {<br>        <strong>view</strong>?.hideLoading()<br>        <strong>view</strong>?.showMovieNotFoundError()<br>    }<br><br>    <strong>private fun </strong>showConnectionError() {<br>        <strong>view</strong>?.hideLoading()<br>        <strong>view</strong>?.showConnectionError()<br>    }<br><br>    ...<br>}</pre><h4>Ventajas</h4><ul><li>Con este enfoque un poco más funcional evitamos el uso de excepciones</li><li>Si añadimos algún caso excepcional a la operación, solo tendríamos que refactorizar nuestra clase GetMovieFailure, actualizar el repositorio para que informara de ese fallo y el presenter para tratarlo. Pero no tendríamos que editar la firma del método execute como si ocurría si utilizamos una función para representar cada situación.</li><li>El código queda más limpio</li><li>Se gana en legibilidad</li><li>En el repositorio y en el caso de uso se expone claramente todas las situaciones posibles, indicando que puede devolver un objeto movie pero también que pueden existir fallos y que tipos de fallos en concreto.</li></ul><h4>Desventajas</h4><ul><li>Una clara desventaja es que hay una curva de aprendizaje en conceptos funcionales, esto se debe tener en cuenta si tú o tu equipo no estáis familiarizados con estos conceptos.</li></ul><h3>Conclusiones</h3><p>Hemos visto distintas opciones que podemos utilizar en Kotlin como alternativas a los callbacks de Java.</p><p>Hay varios factores que pueden afectar para decidirnos a utilizar una alternativa u otra como pueden ser el conocimiento del equipo, tiempos de entrega, tipo de proyecto etc…</p><p>Así que dependiendo del contexto en el que te encuentres puede ser más recomendable una u otra opción.</p><p>El código fuente del código con alguna pequeña variación lo puedes ver <a href="https://github.com/xurxodev/Movies-Kotlin-Kata">aquí</a>.</p><p><strong>¡Gracias por leer este artículo! Si te ha gustado, pulsa el botón </strong>👏🏼 <strong>para que otras personas puedan leerlo también :)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abc1c68f8cf7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blog-de-kirei-studio/alternativas-a-los-callbacks-de-java-en-kotlin-abc1c68f8cf7">Alternativas a los callbacks de Java en Kotlin</a> was originally published in <a href="https://medium.com/blog-de-kirei-studio">Blog de Kirei Studio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Desacoplándonos del uso de co-rutinas en Kotlin]]></title>
            <link>https://medium.com/blog-de-kirei-studio/desacoplandonos-del-uso-de-co-rutinas-en-kotlin-4d229dfafa57?source=rss-c3fe54d1497b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d229dfafa57</guid>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Jorge Sánchez (xurxodev)]]></dc:creator>
            <pubDate>Mon, 09 Apr 2018 05:04:30 GMT</pubDate>
            <atom:updated>2018-04-09T05:04:30.021Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YtksVtOdjE5ESVC3Qc-_NQ.png" /></figure><p>Las co-rutinas fueron <a href="https://kotlinlang.org/docs/reference/whatsnew11.html">añadidas en la versión de Kotlin 1.1</a>, es un librería para realizar programación asíncrona expresando esta lógica de forma secuencial.</p><p>Las co-rutinas implementan, a través de funciones, algunos patrones como async/await, yield, que existe en otros lenguajes para realizar operaciones de larga ejecución (como IO de red, IO de archivo, trabajo intensivo de CPU o GPU, etc.) y normalmente requieren que el llamador se bloqueé hasta que se completen.</p><p><strong>Un punto importante a tener en cuenta es que forma parte del ecosistema de librerías de Kotlin pero no forma parte del lenguaje.</strong></p><p>Las co-rutinas proporcionan una forma de evitar el bloqueo de un hilo y reemplazarlo por una operación más económica y más controlable: la suspensión de una co-rutina.</p><p>Las co-rutinas simplifican la programación asincrónica al encapsular las complicaciones de este tipo de operaciones dentro de la librería.</p><pre>// runs the code in the background thread pool <br><strong>fun</strong> asyncOverlay() = async(CommonPool) {  <br>   <br>   // start two async operations     <br>   <strong>val</strong> original = asyncLoadImage(&quot;original&quot;)     <br>   <strong>val</strong> overlay = asyncLoadImage(&quot;overlay&quot;)     <br>  <br>   // and then apply overlay to both results       <br>   applyOverlay(original.await(), overlay.await()) </pre><pre>}  </pre><pre>// launches new coroutine in UI context <br>launch(UI) {     </pre><pre>   // wait for async overlay to complete     <br>   <strong>val</strong> image =  asyncOverlay().await()    <br> <br>   // and then show it in UI     <br>   showImage(image) </pre><pre>}</pre><h3>Motivos para desacoplarse</h3><p>Algunos de los motivos para querer desacoplarse de las co-rutinas pueden ser:</p><ul><li>La tecnología que utilizamos para realizar tareas asíncronas <strong>es un detalle de implementación</strong>, por lo tanto no es buena idea acoplarnos a los detalles de implementación ya que estos son más inestables normalmente que el dominio de nuestra aplicación.</li><li>No olvidemos que las co-rutinas están en <strong>fase experimental </strong>y es muy posible que haya cambios en futuras releases, como se indica en la <a href="https://kotlinlang.org/docs/reference/coroutines.html">documentación oficial</a>.</li><li>Al ser un detalle de implementación, es importante tener la <strong>flexibilidad de cambiar la forma de ejecutar tareas asíncronas</strong> o incluso poder combinar distintas opciones de forma simple.</li></ul><h3>Dónde utilizar co-rutinas</h3><p>Depende de la arquitectura que estes utilizando, pero normalmente será el punto o los puntos donde en tu aplicación se realizan tareas asíncronas.</p><p>En <a href="http://www.kirei.io/">Kirei Studio</a> solemos utilizar Clean Architecture en desarrollos que requieren de una estructura suficiente como para que tenga sentido.</p><p>Además nosotros en la mayoría de las aplicaciones solo realizamos tareas asíncronas en un punto, salvo alguna excepción, en los casos de uso. A partir de ese punto todo el código es síncrono ganando legibilidad.</p><p>Siguiendo este contexto, sería en los casos de uso donde tendría sentido para nosotros utilizar co-rutinas.</p><pre><strong>class </strong>GetMoviesUseCase(<strong>private val movieRepository</strong>: MovieRepository) {<br><br>    <strong>private var onMoviesLoaded</strong>: (List&lt;Movie&gt;) -&gt; Unit = <strong>{}<br>    private var onConnectionError</strong>: () -&gt; Unit = <strong>{}<br><br>    fun </strong>execute(<br>      onMoviesLoaded: (List&lt;Movie&gt;) -&gt; Unit, <br>      onConnectionError: () -&gt; Unit) {<br>        <strong>this</strong>.<strong>onMoviesLoaded </strong>= onMoviesLoaded<br>        <strong>this</strong>.<strong>onConnectionError </strong>= onConnectionError<br><br>        run();<strong><br>    </strong>}<br><br>    <strong>fun </strong>run() {<br>        async(CommonPool) <strong>{<br></strong>            <strong>try </strong>{<br>                <strong>val </strong>movies = <strong>movieRepository</strong>.getAll()<br><br>                launch(UI) <strong>{onMoviesLoaded</strong>(movies)<strong>}<br>            </strong>} <strong>catch </strong>(ex: Exception) {<br>                launch(UI) <strong>{onConnectionError</strong>()<strong>} <br>            </strong>}<strong><br>        </strong>}<br>    }<br>}</pre><h3>Utilizando una clase base</h3><p>Por lo visto anteriormente, en los motivos para desacoplarse, no es buena idea que cada caso de uso haga uso de las co-rutinas.</p><p>Es algo que te deja bastante claro el IDE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*esz01eoR1Lfbm7IOWQoMFQ.png" /><figcaption>The feature “coroutines” is experimental</figcaption></figure><p>Una posible solución es llevarnos el código relacionado con al ejecución de tareas asíncronas utilizando co-rutinas a una clase base para los casos de uso, creando unas funciones que encapsulen el uso de co-rutinas:</p><pre><strong>abstract class </strong>UseCase (){<br><br>    <strong>fun </strong>uiExecute(uiFun:<strong>suspend </strong>()-&gt;Unit){<br>        <em>launch</em>(<em>UI</em>)<strong>{</strong>uiFun()<strong>}<br>    </strong>}<br>    <strong>fun </strong>asyncExecute(asyncFun:<strong>suspend</strong>()-&gt;Unit){<br>        <em>async</em>(CommonPool) <strong>{</strong>asyncFun()<strong>}<br>    </strong>}<br><br>}</pre><p>Y luego invocar esas funciones de la clase base desde los casos de uso:</p><pre><strong>class </strong>GetMoviesUseCase(<strong>private val movieRepository</strong>:MovieRepository)<br>: UseCase() {<br><br>    <strong>private var onMoviesLoaded</strong>: (List&lt;Movie&gt;) -&gt; Unit = <strong>{}<br>    private var onConnectionError</strong>: () -&gt; Unit = <strong>{}<br><br>    fun </strong>execute(<br>      onMoviesLoaded: (List&lt;Movie&gt;) -&gt; Unit, <br>      onConnectionError: () -&gt; Unit) {<br>        <strong>this</strong>.<strong>onMoviesLoaded </strong>= onMoviesLoaded<br>        <strong>this</strong>.<strong>onConnectionError </strong>= onConnectionError<br><br>        run();<br>    }<br><br>    <strong>fun </strong>run() {<br>        asyncExecute() <strong>{<br>            try </strong>{<br>                <strong>val </strong>movies = <strong>movieRepository</strong>.getAll()<br><br>                uiExecute() <strong>{ onMoviesLoaded</strong>(movies) <strong>}<br>            </strong>} <strong>catch </strong>(ex: Exception) {<br>                uiExecute() <strong>{ onConnectionError</strong>() <strong>}<br>            </strong>}<br>        }<strong><br>    </strong>}<br>}</pre><p>Pero esta solución tiene algunas desventajas:</p><ul><li>Estamos forzando a que todos los casos de uso utilicen co-rutinas para realizar tareas asíncronas. Es posible que por el tipo de tarea que realiza un caso de uso en concreto, fuera más interesante utilizar algún tipo de librería como <a href="https://github.com/yigit/android-priority-jobqueue">priority job queue</a> o similar.</li><li>Aunque los casos de uso no están acoplados directamente a las co-rutinas, si están acoplados indirectamente a través de su clase base.</li></ul><h3>Utilizando una clase externa</h3><p>Utilizar una clase externa, junto además con una abstracción para aplicar <a href="http://xurxodev.com/profundizando-en-la-inversion-de-dependencia/">inversion de dependencia</a>, es la mejor forma de desacoplarnos completamente del uso de co-rutinas y tener la flexibilidad de poder utilizar diferentes librerías para algunos casos de uso, si fuera necesario.</p><p>Así podría ser la abstracción:</p><pre><strong>interface </strong>Executor {<br>    <strong>fun </strong>uiExecute(uiFun:<strong>suspend </strong>()-&gt;Unit)<br>    <strong>fun </strong>asyncExecute(asyncFun:<strong>suspend</strong>()-&gt;Unit)<br>}</pre><p>Posteriormente esta sería su implementación, donde se utilizan co-rutinas:</p><pre><strong>class </strong>CoroutinesExecutor: Executor {<br>    <strong>override fun </strong>uiExecute(uiFun:<strong>suspend </strong>()-&gt;Unit) {<br>        <em>launch</em>(<em>UI</em>) <strong>{<br>            </strong>uiFun()<br>        <strong>}<br>    </strong>}<br><br>    <strong>override fun </strong>asyncExecute(asyncFun:<strong>suspend</strong>()-&gt;Unit) {<br>        <em>async</em>(CommonPool) <strong>{<br>            </strong>asyncFun()<br>        <strong>}<br>    </strong>}<br><br>}</pre><p>El uso de executor quedaría encapsulado dentro de la clase base para los casos de uso, donde además este executor sería inyectado.</p><pre><strong>abstract class </strong>UseCase (<strong>private val executor</strong>: Executor){<br><br>    <strong>fun </strong>uiExecute(uiFun:<strong>suspend </strong>()-&gt;Unit){<br>        <strong>executor</strong>.uiExecute<strong>{</strong>uiFun()<strong>}<br>    </strong>}<br>    <strong>fun </strong>asyncExecute(asyncFun:<strong>suspend</strong>()-&gt;Unit){<br>        <strong>executor</strong>.asyncExecute <strong>{</strong>asyncFun()<strong>}<br>    </strong>}<br><br>}</pre><p>Y en los casos de uso se utilizarían como en el caso anterior las funciones de la clase base al estilo de co-rutinas:</p><pre><strong>class </strong>GetMoviesUseCase(<strong>private val movieRepository</strong>: MovieRepository,<br>                       executor: Executor): UseCase(executor) {<br><br>    <strong>private var onMoviesLoaded</strong>: (List&lt;Movie&gt;) -&gt; Unit = <strong>{}<br>    private var onConnectionError</strong>: () -&gt; Unit = <strong>{}<br><br>    fun </strong>execute(<br>      onMoviesLoaded: (List&lt;Movie&gt;) -&gt; Unit, <br>      onConnectionError: () -&gt; Unit) {<br>        <strong>this</strong>.<strong>onMoviesLoaded </strong>= onMoviesLoaded<br>        <strong>this</strong>.<strong>onConnectionError </strong>= onConnectionError<br><br>        run()<br>    }<br><br>    <strong>fun </strong>run() {<br>        asyncExecute <strong>{<br>            try </strong>{<br>                <strong>val </strong>movies = <strong>movieRepository</strong>.getAll()<br><br>                uiExecute <strong>{ onMoviesLoaded</strong>(movies) <strong>}<br>            </strong>} <strong>catch </strong>(ex: Exception) {<br>                uiExecute <strong>{ onConnectionError</strong>() <strong>}<br>            </strong>}<br>        <strong>}<br>    </strong>}<br>}</pre><h3>Conclusiones</h3><p>Hemos visto los motivos que existen para querer desacoplarnos de las co-rutinas y algunas formas para conseguirlo.</p><p>El ejemplo completo puedes verlo en este <a href="https://github.com/xurxodev/Movies-Kotlin-Kata">repositorio de GitHub</a>.</p><p><strong>¡Gracias por leer este artículo! Si te ha gustado, pulsa el botón </strong>👏🏼 <strong>para que otras personas puedan leerlo también :)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d229dfafa57" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blog-de-kirei-studio/desacoplandonos-del-uso-de-co-rutinas-en-kotlin-4d229dfafa57">Desacoplándonos del uso de co-rutinas en Kotlin</a> was originally published in <a href="https://medium.com/blog-de-kirei-studio">Blog de Kirei Studio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Buenas prácticas con Product Flavors en Android - Parte 3]]></title>
            <link>https://medium.com/blog-de-kirei-studio/buenas-practicas-con-product-flavors-en-android-parte-3-5d95123f08d5?source=rss-c3fe54d1497b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d95123f08d5</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[productflavor]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Jorge Sánchez (xurxodev)]]></dc:creator>
            <pubDate>Mon, 26 Feb 2018 06:05:03 GMT</pubDate>
            <atom:updated>2018-02-26T13:27:04.653Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8oYAg7CnAK1GDvjwr343w.png" /><figcaption>Pantalla de login en dos Product Flavor</figcaption></figure><p>Este artículo es la tercera parte de una serie sobre buenas prácticas trabajando con Product Flavors en Android.</p><p>En el anterior <a href="https://blog.kirei.io/buenas-practicas-con-product-flavors-en-android-parte-2-5834fd176979">artículo</a> vimos un ejemplo donde necesitábamos comunicarnos en cada product flavor con una API distinta y como lo resolvíamos creándonos cada DataSource remoto y los modelos que necesita en cada flavor en lugar de en el directorio main. De esta forma al ser el último eslabón del flujo de ejecución, el flujo de control siempre era de main a Flavor.</p><p>En este artículo vamos a ver otro caso de variación de funcionalidad a resolver cuando se produce en otras etapas del flujo de ejecución.</p><h3>Flujo de control de main a flavor y de flavor a main</h3><p>Normalmente cuando la diferencia de funcionalidad se encuentra en etapas tempranas o intermedias del flujo de ejecución, es normal que creemos una ramificación en el flujo de control siendo este de main a flavor y volviendo en algún punto de nuevo a main.</p><p>Por lo tanto en este escenario <strong>el flujo de control es main a flavor y de flavor a main.</strong></p><h3>Ejemplo</h3><p>Para ver como se puede resolver este tipo de diferencia de funcionalidad vamos a tomar como ejemplo una pantalla de login con distintas funcionalidades entre flavors como en la imagen que hay al principio del artículo.</p><p>Por un lado tenemos el flavor verde con las siguientes funcionalidades:</p><ul><li>Login con email y password</li><li>Registro de usuario</li><li>Modo demo</li></ul><p>Y por otro tenemos el flavor azul con las siguientes funcionalidades:</p><ul><li>Login con email y password</li><li>Registro de usuario</li><li>Login con Facebook</li><li>Login con Google</li></ul><p>Cuando pensamos en la forma de resolver esta diferencia de funcionalidad y de diseño debemos tener presente los limites de código que ya vimos en el <a href="https://blog.kirei.io/buenas-practicas-con-product-flavors-en-android-parte-1-b3618ea1f386">primer artículo</a> de la serie y qué partes son comunes entre flavors y cuales son distintas.</p><p>La opción más drástica es hacerlo todo por separado.</p><p>En cada flavor tendríamos un layout entero distinto, activity distinto, con su presenter distinto etc.. pero existe una funcionalidad visible importante en común como es el login por email y registro de usuario.</p><p>Además podría existir parte en común no tan apreciable a primera vista y más relacionada con detalles técnicos como podría ser configuración del toolbar, menus etc..</p><p>Si tenemos todo por separado en cada flavor estaríamos duplicando mucho código y sería como hacer dos aplicaciones distintas sin aprovecharnos de las ventajas de los product flavors de Android.</p><h3>Resolviendo las diferencias</h3><p>Cuando existe desde la propia interfaz de usuario diferencias entre flavors, algo que resulta muy útil es granular la funcionalidad en clases o conjunto de clases distintas por funcionalidad mínima y entonces ir ubicando lo que sea común en main y lo que que no cada uno en su flavor.</p><p>Granular la funcionalidad en partes pequeñas es siempre buena inversión pero en el contexto de flavors se hace más tangible.</p><h3>Funcionalidad común</h3><p>Existe una funcionalidad común que es Login por email y registro de usuario.</p><p>Esta parte común la alojaremos en el directorio main.</p><h3>Funcionalidad por Flavor</h3><p>La parte inferior de la pantalla de login es la que cambia con cada flavor, aquí puede ser interesante granular y tener dos funcionalidades diferenciadas:</p><ul><li>Demo login</li><li>Login social</li></ul><p>Para tener mayor flexibilidad de cara a futuros cambios es interesante que cada una de estos dos métodos de login tenga una capa de presentación completa.</p><p>Podemos aprovecharnos del uso de los Fragments de Android junto con el patrón strategy para conseguirlo, teniendo cada una de estas dos funcionalidades alojadas en su flavor correspondiente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*kYARB75nMbr67_1pQmcpMw.png" /></figure><p>De forma que según la variante de flavor actual, se representará el fragment de demo login o de login social.</p><h3>Enséñame el código</h3><p>Vamos a ir viendo como quedarían cada uno de los componentes.</p><h3>Layouts</h3><p>Vamos a tener un layout en main que representa la parte común que contiene las vistas para hacer login con email, password y crear nueva cuenta:</p><pre><em>&lt;?</em><strong>xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;</strong><em>?&gt;<br></em>&lt;<strong>LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:orientation=&quot;vertical&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;</strong></pre><pre><strong>    tools:showIn=&quot;@layout/activity_login&quot;</strong>&gt;</pre><pre>    <em>&lt;!-- Email Label --&gt;<br>    </em>&lt;<strong>android.support.design.widget.TextInputLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginTop=&quot;8dp&quot;<br>        android:layout_marginBottom=&quot;8dp&quot;</strong>&gt;</pre><pre>        &lt;<strong>EditText<br>            android:id=&quot;@+id/input_email&quot;<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:inputType=&quot;textEmailAddress&quot;<br>            android:hint=&quot;@string/username_label&quot; </strong>/&gt;<br>    &lt;/<strong>android.support.design.widget.TextInputLayout</strong>&gt;</pre><pre>    <em>&lt;!-- Password Label --&gt;<br>    </em>&lt;<strong>android.support.design.widget.TextInputLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginTop=&quot;8dp&quot;<br>        android:layout_marginBottom=&quot;8dp&quot;</strong>&gt;</pre><pre>        &lt;<strong>EditText<br>            android:id=&quot;@+id/input_password&quot;<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:inputType=&quot;textPassword&quot;<br>            android:hint=&quot;@string/password_label&quot; </strong>/&gt;<br>    &lt;/<strong>android.support.design.widget.TextInputLayout</strong>&gt;</pre><pre>    &lt;<strong>android.support.v7.widget.AppCompatButton<br>        android:id=&quot;@+id/btn_login&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginTop=&quot;24dp&quot;<br>        android:layout_marginBottom=&quot;24dp&quot;<br>        android:padding=&quot;12dp&quot;<br>        android:text=&quot;@string/action_sign_in&quot;<br>        android:enabled=&quot;false&quot; </strong>/&gt;</pre><pre>    &lt;<strong>TextView<br>        android:id=&quot;@+id/link_signup&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginBottom=&quot;24dp&quot;<br>        android:text=&quot;@string/no_account_yet_create_one&quot;<br>        android:gravity=&quot;center&quot;<br>        android:textSize=&quot;16dip&quot; </strong>/&gt;<br>&lt;/<strong>LinearLayout</strong>&gt;</pre><p>El layout para el activity, donde incluimos el layout de login por email y en la parte inferior tenemos un FrameLayout donde aparecerá el fragment según variante de flavor.</p><pre><em>&lt;?</em><strong>xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;</strong><em>?&gt;<br></em>&lt;<strong>ScrollView xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:fitsSystemWindows=&quot;true&quot;</strong>&gt;<br><br>    &lt;<strong>LinearLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:orientation=&quot;vertical&quot;<br>        android:layout_gravity=&quot;center&quot;<br>        android:padding=&quot;24dp&quot;<br>        tools:showIn=&quot;@layout/activity_login&quot;</strong>&gt;</pre><pre>        &lt;<strong>include layout=&quot;@layout/login_by_email_content&quot; </strong>/&gt;<br><br>        &lt;<strong>FrameLayout<br>            android:id=&quot;@+id/additional_login_options_container&quot;<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;match_parent&quot;</strong>/&gt;<br>    &lt;/<strong>LinearLayout</strong>&gt;<br>&lt;/<strong>ScrollView</strong>&gt;</pre><p>Layout para el fragment de demo login:</p><pre>&lt;<strong>LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:orientation=&quot;vertical&quot;</strong>&gt;<br><br>    &lt;<strong>android.support.v7.widget.AppCompatButton<br>        android:id=&quot;@+id/button_demo&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginTop=&quot;16dp&quot;<br>        android:enabled=&quot;false&quot;<br>        android:text=&quot;@string/demo_button&quot; </strong>/&gt;<br><br>&lt;/<strong>LinearLayout</strong>&gt;</pre><p>Y layout para el fragment de login social:</p><pre>&lt;<strong>LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:orientation=&quot;vertical&quot;</strong>&gt;<br><br>    &lt;<strong>android.support.v7.widget.AppCompatButton<br>        android:id=&quot;@+id/button_login_facebook&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginTop=&quot;16dp&quot;<br>        android:enabled=&quot;false&quot;<br>        android:padding=&quot;12dp&quot;<br>        android:text=&quot;@string/sign_in_facebook&quot; </strong>/&gt;<br><br>    &lt;<strong>android.support.v7.widget.AppCompatButton<br>        android:id=&quot;@+id/button_login_google&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginTop=&quot;8dp&quot;<br>        android:text=&quot;@string/sign_in_google&quot; </strong>/&gt;<br><br>&lt;/<strong>LinearLayout</strong>&gt;</pre><h3>Activity, estrategias y fragments</h3><p>En el activity es donde vamos a utilizar el <a href="https://es.wikipedia.org/wiki/Strategy_(patr%C3%B3n_de_dise%C3%B1o)">patrón estrategia</a> para decidir que fragment necesitamos representar en la parte inferior:</p><pre><strong>class </strong>LoginActivity : AppCompatActivity() {<br><br>    <strong>private lateinit var additionalLoginOptionsStrategy</strong>: AdditionalLoginOptionsStrategy</pre><pre>    ...</pre><pre>    <strong>override fun </strong>onCreate(savedInstanceState: Bundle?) {<br>        <strong>super</strong>.onCreate(savedInstanceState)<br><br>        setContentView(R.layout.<em>activity_login2</em>)<br><br>        <strong>additionalLoginOptionsStrategy </strong>=     <br>                          AdditionalLoginOptionsStrategy(<strong>this</strong>)</pre><pre>        <strong>additionalLoginOptionsStrategy</strong>.onCreate(Bundle())<br><br>        initializeLoginButton()<br>    }</pre><pre>    ...</pre><p>La diferencia con el patrón tradicional es que aquí no necesitamos una factoría que nos resuelva la estrategia a crear porque es Gradle al compilar quien se encargará de crear la que corresponda según la variante de flavor actual.</p><p>Estrategia de flavor azul:</p><pre><strong>class </strong>AdditionalLoginOptionsStrategy (<strong>val activity</strong>: Activity){<br>    <strong>fun </strong>onCreate(savedInstanceState: Bundle?){<br>        <strong>val </strong>fragmentManager: FragmentManager =<br>                                        <strong>activity</strong>.<em>fragmentManager</em></pre><pre><em>        </em><strong>val </strong>fragmentTransaction = fragmentManager.beginTransaction()<br><br>        <strong>val </strong>socialLoginFragment: Fragment = SocialLoginFragment()<br>        <br>        fragmentTransaction.add(<br>           R.id.<em>additional_login_options_container</em>, <br>           socialLoginFragment)<br>        <br>        fragmentTransaction.commit()<br>    }<br>}</pre><p>Estrategia de flavor verde:</p><pre><strong>class </strong>AdditionalLoginOptionsStrategy (<strong>val activity</strong>: Activity){<br>    <strong>fun </strong>onCreate(savedInstanceState: Bundle?){<br>        <strong>val </strong>fragmentManager: FragmentManager =<br>                                        <strong>activity</strong>.<em>fragmentManager<br>        </em><strong>val </strong>fragmentTransaction = fragmentManager.beginTransaction()<br><br>        <strong>val </strong>demoLoginFragment: Fragment = DemoLoginFragment()<br>        <br>        fragmentTransaction.add(<br>           R.id.<em>additional_login_options_container</em>, <br>           demoLoginFragment)<br>        <br>        fragmentTransaction.commit()<br>    }<br>}</pre><p>El código de los fragments no tiene ningún misterio, cada uno tendrá su correspondiente presenter y no hay nada excepcional en este ejemplo más allá de que cada uno estará alojado en su flavor correspondiente junto con su presenter etc…</p><h3>Conclusiones</h3><p>En esta tercera parte hemos visto cómo podemos implementar diferencias en funcionalidad entre product flavors desde la capa de presentación y como granular el código por funcionalidad y utilizar el patrón strategy puede sernos de utilidad.</p><h3>Artículos Relacionados</h3><p><a href="https://blog.kirei.io/buenas-practicas-con-product-flavors-en-android-parte-1-b3618ea1f386">Buenas prácticas con Product Flavors en Android - Parte 1</a></p><p><a href="https://blog.kirei.io/buenas-practicas-con-product-flavors-en-android-parte-2-5834fd176979">Buenas prácticas con Product Flavors en Android - Parte 2</a></p><p><strong>¡Gracias por leer este artículo! Si te ha gustado, pulsa el botón </strong>👏🏼 <strong>para que otras personas puedan leerlo también :)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d95123f08d5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blog-de-kirei-studio/buenas-practicas-con-product-flavors-en-android-parte-3-5d95123f08d5">Buenas prácticas con Product Flavors en Android - Parte 3</a> was originally published in <a href="https://medium.com/blog-de-kirei-studio">Blog de Kirei Studio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Buenas prácticas con Product Flavors en Android - Parte 2]]></title>
            <link>https://medium.com/blog-de-kirei-studio/buenas-practicas-con-product-flavors-en-android-parte-2-5834fd176979?source=rss-c3fe54d1497b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5834fd176979</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[productflavor]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Jorge Sánchez (xurxodev)]]></dc:creator>
            <pubDate>Sun, 14 Jan 2018 18:47:29 GMT</pubDate>
            <atom:updated>2018-02-26T13:25:54.898Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*2KYYxft_K15n1EjNhu6OKw.png" /><figcaption>Product Flavors diferente API</figcaption></figure><p>Este artículo es la segunda parte de una serie sobre buenas prácticas trabajando con Product Flavors en Android.</p><p>En el anterior <a href="https://blog.kirei.io/buenas-practicas-con-product-flavors-en-android-parte-1-b3618ea1f386">artículo</a> introducimos el concepto de Product Flavor.</p><p>Vimos para qué puede ser útil y como se pueden abordar en los flavors las diferencias entre ellos cuando se trata de recursos o de funcionalidad.</p><h3>Separando responsabilidades</h3><p>Respecto a las diferencias en funcionalidad vimos que la opción más básica es utilizar la variable de compilación FLAVOR o variables de compilación personalizadas.</p><p>Utilizar variables de compilación es buena idea cuando no requiere realizar diferentes bloques de código en base a una condición, por ejemplo cuando pasamos el valor de la variable de compilación como parámetro de una factoría o algo similar.</p><p>Si el uso de la variable de compilación requiere hacer una condición, estaríamos incumpliendo algunos principios SOLID con los problemas que trae consigo de cara a la evolución los productos en el futuro.</p><p>A medida que el código dependiente de la variable de compilación es más grande, el problema se incrementa.</p><p><strong>Cuando tenemos diferentes funcionalidades entre Product Flavors es recomendable que separemos estas responsabilidades</strong>.</p><p>Podemos separar en forma de clases, paquetes o una combinación de ambas.</p><h3>Limitaciones</h3><p>Recordemos que existen una serie limitaciones cuando trabajamos con ficheros de código en Product flavors en Android:</p><ul><li><strong>No puede existir una clase con el mismo nombre en el directorio de un flavor y en main</strong>. Pero si podemos tener una misma clase duplicada por cada flavor y al compilar se utiliza la que corresponde según la variante de flavor que estemos compilando.</li><li><strong>Si creo una clase por cada flavor que se invocará desde main, todos los flavors deben contener esa clase</strong>. De lo contrario, al trabajar con una variante de flavor que no contiene una clase que debe ser invocada desde main, para esa variante dará error de compilación porque no encontrará esa clase.</li></ul><h3>Flujo de control, siempre, de main a flavor</h3><p>Cuando la funcionalidad diferente encaja en el ámbito de una clase o un paquete completo lo mas sencillo es que esa clase o paquete entero existan por separado en cada uno de los flavors y no exista en el main nada referente a ese paquete o clase ni código compartido entre esos paquetes salvo alguna abstracción.</p><p>Por lo tanto con esta técnica no existirá lógica común entre esas clases de los flavors.</p><p>Si además coincide que este ámbito donde se encuentra la diferencia se sitúa en la capa de datos, nos encontramos en el último eslabón del flujo de ejecución, entonces <strong>el flujo de control es siempre de de main a flavor.</strong></p><p>Desde main invocamos métodos de clases que se encuentran en cada flavor pero desde los flavors no se invocan métodos definidos en main.</p><h3>Ejemplo</h3><p>Imaginemos una aplicación sobre películas, y que en cada flavor debe obtener los datos de una api distinta.</p><p>En este escenario vamos a tener en el directorio main una serie de clases comunes a los dos flavors como son: activities, fragments, presenters, casos de uso, entidades de dominio, repositorios etc...</p><p>Sin embargo cuando entramos en el terreno de la capa de datos y más concretamente de la comunicación con la API de servidor remoto, es decir, las clases que recuperan los datos de una API, tenemos una variación entre los product flavors porque hay que comunicarse con dos API diferentes para cada uno.</p><p>Podríamos tener en cada flavor un paquete <em>..data.remote </em>y en este paquete tendríamos DataSources, Services de Retrofit, modelos de respuesta de la api y mappers adecuados para cada API.</p><p>Una posible, que no la única, aproximación en cuanto a estructura del proyecto podría ser así:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*oMTsjrA8fSPXqy4sQkwKeg.png" /><figcaption>Product Flavors sin código común</figcaption></figure><p>Como vamos a tener dos data sources remotos como puerta de entrada a cada flavor y deben tener los mismos métodos y respuestas, es interesante tener en el directorio main un interface que deban implementar ambos.</p><pre><strong>interface </strong>MovieRemoteDataSource {<br>    <strong>fun </strong>getById(id: String): Movie<br>}</pre><p>Este interface no es obligatorio porque la implementación de cada DataSource tiene el mismo nombre y gradle se encarga de utilizar el que corresponde según la variante de compilación activa.</p><p>Sin embargo si es recomendable tenerlo en main para que lo implementen los DataSource remotos ubicados dentro de cada flavor.</p><p>De esta forma se simplifica el hecho de enterarnos cuando no estamos implementando un método o cuando la firma de uno en concreto no es exactamente como se espera en el repositorio.</p><p>Cuando tengamos ese fichero abierto, el IDE nos muestra un warning si estamos incumpliendo el contrato definido en el interface ubicado en el directorio main.</p><p>De lo contrario tendríamos que esperar a compilar o ejecutar para que el IDE nos avise que un repositorio esta intentando invocar un método que no existe en el DataSource remoto del flavor actual o que la firma no coincide.</p><p>En cada flavor tendríamos las clases dependientes de cada api de servidor.</p><p>Estas serían las clases para el product Flavor 1:</p><pre>// Retrofit api service <br>//http://www.omdbapi.com?apikey={apiKey}&amp;i={i}<br><strong>interface </strong>OMDbService {<br>    @GET(<strong>&quot;/&quot;</strong>)<br>    <strong>fun </strong>getMovie(@Query(<strong>&quot;apikey&quot;</strong>) apiKey: String,<br>                 @Query(<strong>&quot;i&quot;</strong>) id: String): Call&lt;OMDbMovie&gt;;<br>}</pre><pre>// API Model<strong><br>data class </strong>OMDbMovie(<strong>val title</strong>: String,<br>                     <strong>val year</strong>: String?,<br>                     <strong>val rated</strong>: String,<br>                     <strong>val director</strong>: String,<br>                     <strong>val actors</strong>: String,<br>                     <strong>val plot</strong>: String,<br>                     <strong>val language</strong>: String,<br>                     <strong>val country</strong>: String,<br>                     <strong>val awards</strong>: String?,<br>                     <strong>val poster</strong>: String?)</pre><pre>// The Open Movie Database Data Source<br><strong>class </strong>MovieAPIDataSource (retrofit: Retrofit) : MovieRemoteDataSource {<br><br>    <strong>private val omdbService </strong>= retrofit.create(OMDbService::<strong>class</strong>.<em>java</em>)<br><br>    <strong>override fun </strong>getById(id: String): Movie {<br>        <strong>val </strong>response  = <strong>omdbService</strong>.getMovie(<strong>&quot;apikey&quot;</strong>,id).execute()<br><br>        <strong>return </strong>mapMovie(response.body());<br>    }<br><br>    <strong>private fun </strong>mapMovie(omdbMovie: OMDbMovie): Movie {<br>        <em>//.. Map to movie ..<br>        with</em>(omdbMovie)<strong>{<br>            return </strong>Movie(<strong>title</strong>,<strong>year</strong>,<strong>plot</strong>,<strong>language</strong>,<strong>country</strong>,<strong>poster</strong>);<br>        <strong>}<br>    </strong>}<br>}</pre><p>Estas serían las clases para el product Flavor 2:</p><pre>// Retrofit api service //https://api.themoviedb.org/3/movie/{movie_id}?apikey={apiKey}<br><strong>interface </strong>TMDbService {<br>    @GET(<strong>&quot;/movie/{movie_id}&quot;</strong>)<br>    <strong>fun </strong>getMovie(@Query(<strong>&quot;apikey&quot;</strong>) apiKey: String,<br>                 @Path(<strong>&quot;movie_id&quot;</strong>) id: String): Call&lt;TMDbMovie&gt;;<br>}</pre><pre>// API Model<br><strong>data class </strong>TMDbMovie(<strong>val title</strong>: String,<br>                     <strong>val year</strong>: String?,<br>                     <strong>val rate</strong>: String,<br>                     <strong>val director</strong>: String,<br>                     <strong>val actors</strong>: String,<br>                     <strong>val plot</strong>: String,<br>                     <strong>val lang</strong>: String,<br>                     <strong>val country</strong>: String,<br>                     <strong>val image</strong>: String?)</pre><pre>// The Movie DB Data Source<br><strong>class </strong>MovieAPIDataSource(retrofit: Retrofit) : MovieRemoteDataSource {<br><br>    <strong>private val tmdbService </strong>= retrofit.create(TMDbService::<strong>class</strong>.<em>java</em>)<br><br>    <strong>override fun </strong>getById(id: String): Movie {<br>        <strong>val </strong>response = <strong>tmdbService</strong>.getMovie(<strong>&quot;apikey&quot;</strong>, id).execute()<br><br>        <strong>return </strong>mapMovie(response.body());<br>    }<br><br>    <strong>private fun </strong>mapMovie(tmdbMovie: TMDbMovie): Movie {<br>        <em>//.. Map to movie ..<br>        with</em>(tmdbMovie)<strong>{<br>            return </strong>Movie(<strong>title</strong>, <strong>year</strong>, <strong>plot</strong>, <strong>lang</strong>, <strong>country</strong>, <strong>image</strong>);<br>        <strong>}<br>    </strong>}<br>}</pre><p>El repositorio se comunicaría con el data source remoto según la variable de compilación, pero de eso se encarga Gradle :)</p><pre><strong>class </strong>CachedMovieRepository: MovieRepository {<br>    <br>    <em>//...<br>    <br>    </em><strong>override fun </strong>getById(id: String): Movie {<br>        <em>//..<br><br>        </em><strong>val </strong>movie = <strong>remoteDataSource</strong>.getById(id)<br><br>        <em>//..<br>    </em>}<br><br>    <em>//...<br></em>}</pre><h3>Conclusiones</h3><p>En esta segunda parte hemos visto cómo podemos implementar diferencias en funcionalidad entre product flavors cuando esta es completamente distinta en el ámbito de una clase o paquete y pertenece a la capa de datos.</p><p>Es futuras entregas veremos cómo poder afrontar diferentes situaciones como por ejemplo cuando la diferencia no es completamente distinta en el ámbito de una clase o paquete y también cuando entre los product flavors necesitan compartir código.</p><h3>Artículos Relacionados</h3><p><a href="https://blog.kirei.io/buenas-practicas-con-product-flavors-en-android-parte-1-b3618ea1f386">Buenas prácticas con Product Flavors en Android - Parte 1</a></p><p><a href="https://blog.kirei.io/buenas-practicas-con-product-flavors-en-android-parte-3-5d95123f08d5">Buenas prácticas con Product Flavors en Android - Parte 3</a></p><p><strong>¡Gracias por leer este artículo! Si te ha gustado, pulsa el botón </strong>👏🏼 <strong>para que otras personas puedan leerlo también :)</strong></p><p>Imagen del diseño de la app móvil: <a href="https://dribbble.com/shots/2131805-Movie-App-UI">https://dribbble.com/shots/2131805-Movie-App-UI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5834fd176979" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blog-de-kirei-studio/buenas-practicas-con-product-flavors-en-android-parte-2-5834fd176979">Buenas prácticas con Product Flavors en Android - Parte 2</a> was originally published in <a href="https://medium.com/blog-de-kirei-studio">Blog de Kirei Studio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Buenas prácticas con Product Flavors en Android - Parte 1]]></title>
            <link>https://medium.com/blog-de-kirei-studio/buenas-practicas-con-product-flavors-en-android-parte-1-b3618ea1f386?source=rss-c3fe54d1497b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3618ea1f386</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Jorge Sánchez (xurxodev)]]></dc:creator>
            <pubDate>Mon, 20 Nov 2017 05:36:33 GMT</pubDate>
            <atom:updated>2018-02-26T13:23:58.019Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*hU-YcaICGUED9vv_TiB1Og.png" /><figcaption>Product Flavors</figcaption></figure><p>Product flavors es similar a tener diferentes tipos de compilación (Debug, Release) pero se utilizan para crear diferentes productos apk, de un mismo proyecto Android.</p><p>Dos posibles utilidades que tienen los product flavors pueden ser:</p><ul><li>Tener una versión gratis y otra de pago.</li><li>Tener un producto estándar común y un flavor por cada app de cliente con sus personalizaciones.</li></ul><p>En este artículo no voy a explicar como se configuran los flavors, existen muchos artículos en internet que explican como se hace. Por ejemplo os dejo la <a href="https://developer.android.com/studio/build/build-variants.html?#product-flavors">documentación oficial</a> de Android.</p><p>Este artículo es la primera parte de una serie donde voy explicar diferentes técnicas que podemos utilizar cuando queremos hacer diferencias entre flavors de nuestro proyecto.</p><p>Por cada product flavor se genera una variante de compilación que vamos a poder compilar por separado y podemos crear una estructura de paquetes igual que la existe colgando de main por cada flavor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*doWygUrCLsQph3UJGqhknQ.png" /></figure><p>Después eligiendo la variante de compilación en el panel Build Variants, ya podemos trabajar con un flavor en concreto.</p><h3>Diferencias en recursos</h3><p>Tener diferentes recursos entre product flavors es sencillo, por cada product flavor podemos tener un directorio de recursos y por lo tanto podemos tener duplicado un recurso en cada flavor.</p><p><strong>Es posible tener un recurso por defecto en el paquete main y personalizaciones opcionales duplicadas en cada variante de flavor</strong>.</p><p>Si no existe un recurso personalizado en la variante de flavor actual se utilizará el que existe en main.</p><p>Por ejemplo podemos tener un fichero colors.xml en cada flavor especificando los colores de cada variante.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pWQ4DNtIrZl0JPM3ba7Sbw.png" /><figcaption>Recursos por variante</figcaption></figure><p>De esta forma podremos tener dos apk y cada uno con sus colores.</p><h3>Diferencias en funcionalidad</h3><p>Tener diferencias en la funcionalidad es un poco más complejo, también podemos tener un directorio java por cada flavor pero existen limitaciones en cuando al directorio main y los flavors:</p><ul><li><strong>No puede existir una clase con el mismo nombre en el directorio de un flavor y en main</strong>. Pero si podemos tener una misma clase duplicada por cada flavor y al compilar se utiliza la que corresponde según la variante de flavor que estemos compilando.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3HXVGAevUaPw9ipNp9dVHw.png" /></figure><ul><li><strong>Si creo una clase por cada flavor que se invocará desde main, todos los flavors deben contener esa clase</strong>. De lo contrario, al trabajar con una variante de flavor que no contiene una clase que debe ser invocada desde main, para esa variante dará error de compilación porque no encontrará esa clase.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v0VOL4CdYeIH1tsSeRZQsw.png" /></figure><p>Existen distintas opciones para poder realizar personalizaciones de funcionalidad en los flavors.</p><h3>Variables de compilación</h3><p>La forma más sencilla de ejecutar un código distinto en función del flavor es utilizar las variables de compilación, tenemos dos opciones:</p><ul><li><strong>Variable de compilación FLAVOR</strong></li></ul><p>Cuando trabajamos con flavors, existe una variable de compilación FLAVOR que se crea por defecto, de tipo string y contiene el texto de la variante de flavor actual.</p><pre><strong>if </strong>(BuildConfig.<em>FLAVOR</em>.equals(<strong>&quot;cliente1&quot;</strong>)){<br>    <br>}<strong>else</strong>{<br>    <br>}</pre><ul><li><strong>Variable de compilación personalizada</strong></li></ul><p>También nos podemos crear una variable de compilación personalizada y asignarle un valor distinto para cada flavor.</p><p>Estas variables personalizadas se definen en el fichero build.gradle del módulo de aplicación.</p><p>Se definen dentro de la sección de cada flavor, se asigna el tipo de dato y el valor.</p><pre>productFlavors {<br>    cliente1 {<br>        ...<strong><br>        </strong>buildConfigField <strong>&quot;boolean&quot;</strong>, <strong>&quot;allowedConfigurePushNotifications&quot;</strong>, <strong>&quot;true&quot;<br>    </strong>}<br>    cliente2 {<br>        ......<strong><br>        </strong>buildConfigField <strong>&quot;boolean&quot;</strong>, <strong>&quot;allowedConfigurePushNotifications&quot;</strong>, <strong>&quot;false&quot;</strong></pre><pre><strong>    </strong>}<br>}</pre><p>Desde el código se consulta de la misma forma que las variables de compilación por defecto.</p><pre><strong>if </strong>(BuildConfig.allowedConfigurePushNotifications){<br>    <br>}<strong>else</strong>{<br>    <br>}</pre><p>Utilizar variables de compilación para introducir variaciones de funcionalidad en nuestro flavors, salvo alguna excepción o caso sencillo, no es muy buena práctica.</p><p>Si utilizamos condiciones mediante variables de compilación se empiezan a incumplir unos cuantos principios SOLID con los problemas que esto conlleva:</p><ul><li><strong>Principio de responsabilidad única</strong>, este principio se incumple porque dentro de una clase existe código para n flavors. Cada flavor es una responsabilidad diferente claramente.</li><li><strong>Principio de abierto cerrado</strong>, este principio se incumple porque si queremos añadir nuevos flavors vamos a tener que modificar código para los flavors existentes. Por lo tanto no esta cerrado a la modificación y abierto a la extensión.</li></ul><h3>Separando responsabilidades</h3><p>Aunque el compilado final son n aplicaciones distintas, podemos visualizar las variaciones de funcionalidad de cada flavor como estrategias distintas de una misma aplicación.</p><p>Desde este punto de vista, cada flavor es una responsabilidad distinta y por lo tanto, es más interesante tener el código que representa a cada flavor separado del resto.</p><p>De esta forma empezamos a cumplir los principios SOLID y nuestro proyecto empieza a ser más escalable.</p><h3>Flujo de control</h3><p>Recordemos que si queremos tener diferente funcionalidad entre flavors tenemos algunas limitaciónes:</p><ul><li><strong>No puede existir una clase con el mismo nombre en los flavors y en main</strong>.</li><li><strong>Si creo una clase por flavor que se invoca desde main, todos los flavors deben contener esa clase</strong>. De lo contrario al trabajar con una variante de flavor que no contiene una clase, al ser invocada desde main, esa variante no compilaría.</li></ul><p>El flujo de control según la wikipedia significa esto:</p><blockquote>In <a href="https://en.wikipedia.org/wiki/Computer_science">computer science</a>, <strong>control flow</strong> (or <strong>flow of control</strong>) is the order in which individual <a href="https://en.wikipedia.org/wiki/Statement_(computer_science)">statements</a>, <a href="https://en.wikipedia.org/wiki/Instruction_(computer_science)">instructions</a> or <a href="https://en.wikipedia.org/wiki/Function_call">function calls</a> of an imperative <a href="https://en.wikipedia.org/wiki/Computer_program">program</a> are <a href="https://en.wikipedia.org/wiki/Execution_(computing)">executed</a> or evaluated.</blockquote><p>Según el contexto en el que nos encontremos, existen factores que nos determinan la mejor estrategia a seguir como pueden ser:</p><ul><li>Arquitectura de nuestra aplicación.</li><li>Grado de funcionalidad diferente entre flavors.</li><li>En que clase o componente se encuentra la diferencia (Activity, Fragment, CustomView o una clase ajena al framework de Android).</li></ul><p>Y la decisión que tomemos nos puede llevar por dos caminos en cuanto al flujo de control:</p><ul><li>Flujo de control, siempre, de main a flavor</li><li>Flujo de control, en ocasiones, de flavor a main</li></ul><p>Pero esto lo veremos en la segunda parte de esta serie :)</p><h3>Conclusiones</h3><p>En esta primera parte hemos visto en que consiste el concepto de flavor y las técnicas más sencillas de personalización que podemos utilizar para realizar diferencias, en cada flavor, en cuanto a recursos y funcionalidad.</p><p>También hemos visto las limitaciones que tenemos respecto al código en los flavors que no existe con los recursos.</p><p>En la segunda parte veremos técnicas un poco más complejas y como puede afectar al flujo de control la opción que escojamos.</p><h3>Artículos Relacionados</h3><p><a href="https://blog.kirei.io/buenas-practicas-con-product-flavors-en-android-parte-2-5834fd176979">Buenas prácticas con Product Flavors en Android - Parte 2</a></p><p><a href="https://blog.kirei.io/buenas-practicas-con-product-flavors-en-android-parte-3-5d95123f08d5">Buenas prácticas con Product Flavors en Android - Parte 3</a></p><p><strong>¡Gracias por leer este artículo! Si te ha gustado, pulsa el botón </strong>👏🏼 <strong>para que otras personas puedan leerlo también :)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3618ea1f386" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blog-de-kirei-studio/buenas-practicas-con-product-flavors-en-android-parte-1-b3618ea1f386">Buenas prácticas con Product Flavors en Android - Parte 1</a> was originally published in <a href="https://medium.com/blog-de-kirei-studio">Blog de Kirei Studio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>