<?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 Alperen Babagil on Medium]]></title>
        <description><![CDATA[Stories by Alperen Babagil on Medium]]></description>
        <link>https://medium.com/@babagilalperen?source=rss-97ca014e3401------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fGAAv40B6bBaGi3JmhpWGA.jpeg</url>
            <title>Stories by Alperen Babagil on Medium</title>
            <link>https://medium.com/@babagilalperen?source=rss-97ca014e3401------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 10:08:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@babagilalperen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Android Clean App Base Library (Clean Architecture + MVVM) - Part I]]></title>
            <link>https://medium.com/huawei-developers/android-clean-app-base-library-clean-architecture-mvvm-part-i-e8614978877f?source=rss-97ca014e3401------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8614978877f</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[libraries]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alperen Babagil]]></dc:creator>
            <pubDate>Thu, 26 Nov 2020 21:19:32 GMT</pubDate>
            <atom:updated>2020-11-27T07:50:21.261Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-4ZuRkMPj8r_QMXYnzd2Iw.jpeg" /><figcaption>Clean App Base</figcaption></figure><p>Hello everyone 🙋‍♂️ In this medium series I will talk about Clean Architecture in Android Development. Then I will explain my library: a base library for clean architecture projects. Finally I will show my tech stack that I used in my library and demo app that uses that library. Library and demo app is hosted on my github:</p><p><a href="https://github.com/alperenbabagil/cleanappbase">alperenbabagil/cleanappbase</a></p><p>It is written with Kotlin in modular way. So you can use it some of its layers or all layers at once.</p><p>List of my tech stack: <a href="https://kotlinlang.org/">Kotlin</a>, <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">Clean Architecture</a>, <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel">MVVM</a>, <a href="https://kotlinlang.org/docs/reference/coroutines-overview.html">Kotlin Coroutines</a>, <a href="https://medium.com/swlh/repository-pattern-in-android-c31d0268118c">Repository Pattern</a>, Dependency Injection with <a href="https://github.com/InsertKoinIO/koin">Koin</a>, <a href="https://developer.android.com/topic/libraries/data-binding">Data Binding</a>, Unit testing up to Activity/Fragment with <a href="https://mockk.io/">MockK</a>, <a href="https://github.com/coil-kt/coil">Coil </a>for image loading, <a href="https://square.github.io/retrofit/">Retrofit2</a>, <a href="https://github.com/natario1/Elements">Elements </a>library for using RecyclerView.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F5zf2M4HgjjWszLd4a5%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F5zf2M4HgjjWszLd4a5%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExODhsMmNqYnZpYnNocjd3MTFkd2k2Mm96dzEwbTg2OGdwcGplMzQ1bSZlcD12MV9naWZzX2dpZklkJmN0PWc%2F5zf2M4HgjjWszLd4a5%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="181" frameborder="0" scrolling="no"><a href="https://medium.com/media/ceb4fd2380af661521a6e88c61bea3a3/href">https://medium.com/media/ceb4fd2380af661521a6e88c61bea3a3/href</a></iframe><h3>What is Clean Architecture?</h3><p>Clean Architecture is a software design concept proposed by Robert C. Martin and promoted on his blog, Uncle Bob. It says an application must meet customer’s needs with providing flexibility, testability, and maintainability. It divides software into layers with defining rules about communication between them. It is the famous chart of it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*uQYJsu2agzmjp9s_eEieeA.png" /><figcaption>The Clean Code Blog by Robert C.Martin (Uncle Bob)</figcaption></figure><p>According to this chart a circle must only know the next inner circle. Data flow must be inner circle to outer. Basic data interaction and flow must like this:</p><p>1- Presentation triggered by Framework &amp; Drivers layer. That can be user input, push notification, DB change callback etc.</p><p>2- Presentation layer executes Use case. This layer also determines life cycle of execution.</p><p>3- Use case must ask Entity layer for data and wait for the result</p><p>4- Entity provides data source. At this point the entity is independent from application logic and works with enterprise logic.</p><p>5- After attempt to getting data Entity layer must return data or fail reason to Use case layer.</p><p>6- Use case must return this data and data state to Presentation layer. After this point Presentation has nothing to do with inner the circle.</p><p>7- Presentation layer uses data to inform the user and waits for other triggers.</p><h3>Should I use it?</h3><p>According to general opinion, it must be used at large and medium scale projects. For small scale projects it is considered as an overkill. But in my opinion it must be the default project structure for all projects. It provides excellent testability for apps. Besides it defines your classes and their responsibilities. So another developer easily understands which class does what. Additionally, all small scale projects evolve to medium as I observed. So:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxUySTM4M5W2JdeeMxO%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxUySTM4M5W2JdeeMxO%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FxUySTM4M5W2JdeeMxO%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/31acb93b24a0122de5541891009dac8b/href">https://medium.com/media/31acb93b24a0122de5541891009dac8b/href</a></iframe><h3>In Android World</h3><p>In Android we have Activities, Fragments, Intents, Services, Threads and Lifecycles. All components that we want to run away because these components are mostly system related and have unpredictable behaviours. Because mobile platform is a living thing and affected by the outside world. So we must create our clean architecture components such as layers, use cases, rules, entities etc. Additionally all program logic must not live in Activities/Fragments. It creates god objects that are hard to test and maintain.</p><p>Our structure is divided as 3 layers in Android: <strong>Data</strong>, <strong>Domain </strong>and <strong>Presentation</strong>. You can implement it as 3 main modules and separate futures in this module. Or you can divide your app into feature modules and create data-domain-presentation packages/modules in it. It is up to you. Below I will try to explain these layers with more familiar classes.</p><h4>1- Domain Layer</h4><p>Domain layer is the center of our structure, it connects the data and presentation layer. Ina a modular way data only knows domain layer same as presentation. Because data layer is irrelevant and replaceable for our app, it must work with app models. It contains general a stateful data container model (<strong>DataHolder</strong>) known by all layers and Use cases (I will call it <strong>Interactor </strong>from now on). Interactors must have a single purpose: get one type of data from data layer and pass it to presentation layer. If execution needs parameter(s) it must be special for that interactor so changes at data or presentation must affect maximum 2 layers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75d45ca51c081e2ff36360c1c1e6f897/href">https://medium.com/media/75d45ca51c081e2ff36360c1c1e6f897/href</a></iframe><p>In my way I don’t use any threading logic and keep interactors as simple as possible. They are more like defined rules about getting data with specified types. They consist of suspend functions that calls related repository (what the h*ll is a repository?)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/457db2abed437d051674f48cac6afc7c/href">https://medium.com/media/457db2abed437d051674f48cac6afc7c/href</a></iframe><p>Repository has getting data logic and actually belongs to the data layer but it’s definition resides in domain layer because interactor must know it. I will talk about in data layer.</p><h4>2- Data Layer</h4><p>Data layer handles all enterprise logic and produces data for our app. All complex logic must belong here. It must also be as independent as possible from platform. So it can be unit tested and modifiable. It mainly consists of 3 parts: <strong>Data Source</strong>, <strong>Repository Implementation</strong> and <strong>Mapper</strong>.</p><p>Data source is responsible for getting one type of data. Does mostly the hard work of this layer. It can communicate with the server or do the text recognition etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99aca5d8e8cf6555eb01c2d2bd717c05/href">https://medium.com/media/99aca5d8e8cf6555eb01c2d2bd717c05/href</a></iframe><p>Repository Implementation is a type of repository which resides in domain layer. It’s duty is manage data sources and provide app objects to the interactor. It can use more than data source to get all data reordered joined and mapped to app models defined in domain layer with help of mappers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2163b6195ff96fb3b10f48a3ab511b76/href">https://medium.com/media/2163b6195ff96fb3b10f48a3ab511b76/href</a></iframe><p>Mappers are used to convert enterprise objects to app objects or app requests to enterprise requests. Let’s say app model to be sent to server has <strong>Date</strong> class. But server accept this field as a formatted string. Mapper makes possible this conversion.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b65395b8960c69b5a49a94a0fa3d88a3/href">https://medium.com/media/b65395b8960c69b5a49a94a0fa3d88a3/href</a></iframe><h4>3- Presentation Layer</h4><p>Presentation layer is the most familiar layer to us, it contains activities, fragments and view models etc. This layer has two responsibilities: get triggered then request data and show data that comes from domain layer. Additionally this is the layer that system gives resources to run your app. Calls your lifecycle calbacks, broadcasts events etc. But has many states to be carefully managed. That means things can be get messy if code logic piled up here. Besides it makes impossible to unit test your code.</p><p>MVVM structure is a good way to make presentation layer reliable . Using view model is the key point. It reduces lifecycle effects and gives an coroutine scope easily (<strong>viewModelScope</strong>). In my design it executes interactors in desired coroutine scope and post it to a live data as <strong>DataHolder</strong>. Then this live data observed in activity/fragment and necessary UI operations performed according to it’s success/fail/loading state. By that way activity/fragment only knows and observes view model, that separates framework from inner circle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fceeeab4ca1f955deb357431562d075/href">https://medium.com/media/1fceeeab4ca1f955deb357431562d075/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44e662146c3a4ed3c79a08f157fa7ff7/href">https://medium.com/media/44e662146c3a4ed3c79a08f157fa7ff7/href</a></iframe><p>All threading logic handled in view model because it follows it’s presenter’s lifecycle. Usually we need data if we are looking related screen at that moment. When a screen finished related view model is closed and it cancels it’s data getting process automatically and safely.</p><h3>Too many classes… How can I manage them?</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F1n59if8EmpiBNIvRQx%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F1n59if8EmpiBNIvRQx%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F1n59if8EmpiBNIvRQx%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="242" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e1d95d2f8ef97ae464991ffc427ff49/href">https://medium.com/media/7e1d95d2f8ef97ae464991ffc427ff49/href</a></iframe><p>As our app grows, number of instances and classes to get data increases. We create data sources, repositories, interactors, mappers… for every type of models. Instance creation and lifecycle management of this this classes requires huge amount of code and prone to generating bugs.</p><p>The answer is <strong>Dependency Injection</strong>. It creates object instances for you and keeps them in the memory as long as they are needed. Thanks to the DI, we put needed class interfaces into our constructor and just use it. By this way a class does only its job, nothing more (Separation of concerns). Because of the tools class needed comes from outside, unit testing our class as easy as shelling peas.</p><p>I usually use <a href="https://github.com/InsertKoinIO/koin">Koin</a> for dependency injection. It is easy to set up and makes great job with little piece of code. Here is an example to one of my demo app’s modules.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1c021b356475f424b90566c6cdfdf45/href">https://medium.com/media/a1c021b356475f424b90566c6cdfdf45/href</a></iframe><p>This module creates all needed classes for my main data layer (I will explain this app in detail at next parts). <strong>UserRepositoryImpl </strong>needs <strong>GetUserDataDataSource</strong>. <strong>GetUserDataDataSource </strong>needs a <strong>UserService</strong> retrofit and an <strong>ApiCallAdapter</strong>. If you noticed there is no information about creation of <strong>ApiCallAdapter</strong>. It resides another module and because of modules are connected eventually, it can create <strong>ApiCallAdapter </strong>for all modules. This is how DI makes our life easier and reduces our boilerplate code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*gp9XfkJys25zmHtNd8M-1g.png" /></figure><p>That was the Part <strong>I</strong>. In part <strong>II</strong>, I will talk about Clean App Base library that I made to get rid of duplicate code for clean architecture projects. In part <strong>III </strong>&amp; <strong>I</strong>V will explain Demo app that uses Clean App Base Library ,tools and unit testing.</p><p>Happy coding 🎉</p><p><strong>Part II:</strong></p><p><a href="https://babagilalperen.medium.com/android-clean-app-base-library-clean-architecture-mvvm-part-ii-e4ab489838a8">Android Clean App Base Library (Clean Architecture + MVVM) — Part II</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8614978877f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/huawei-developers/android-clean-app-base-library-clean-architecture-mvvm-part-i-e8614978877f">Android Clean App Base Library (Clean Architecture + MVVM) - Part I</a> was originally published in <a href="https://medium.com/huawei-developers">Huawei Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Clean App Base Library (Clean Architecture + MVVM) — Part II]]></title>
            <link>https://medium.com/huawei-developers/android-clean-app-base-library-clean-architecture-mvvm-part-ii-e4ab489838a8?source=rss-97ca014e3401------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4ab489838a8</guid>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[libraries]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alperen Babagil]]></dc:creator>
            <pubDate>Thu, 26 Nov 2020 21:18:45 GMT</pubDate>
            <atom:updated>2020-11-26T21:30:36.525Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/p/e8614978877f/edit?source=your_stories_page-------------------------------------">Android Clean App Base Library (Clean Architecture + MVVM) — Part II</a></h3><p>Hello everyone🙋‍♂️ In this part I will show you my Clean App Base Library. It mainly consists of base classes for the structures that I talked about Part <a href="https://medium.com/p/e8614978877f/edit?source=your_stories_page-------------------------------------">I</a> and some base methods to reduce our code one line in some places. Here is a link of my lib:</p><p><a href="https://github.com/alperenbabagil/cleanappbase">alperenbabagil/cleanappbase</a></p><p>You can find here the source code and installation instructions.</p><h3>Motivation</h3><p>Firstly, whenever I start a project I was creating the same base classes for the same reasons. Because I use clean architecture, there are many classes. This library saves developer from creating classes again and again.</p><p>Secondly, especially in presentation showing data that comes from domain level requires lots of code. Most basic flow is like this: Activity requests some data to show. By the meantime it must show a loading indicator. For this it observes a live data from view model. That live data returns <strong>DataHolder&lt;T&gt;</strong> . Activity then behaves differently according to the data holder’s type. If it is Success, uses data. If it is Loading, shows loading indicator. If it is Fail shows some error dialog. That was the observer side. In the view model firstly observed data holder’s value must set be to <strong>DataHolder.Loading</strong>. Then the interactor must be executed in view model scope. Then coming data must be passed to observed live data. Of course that execution can be more parametrized. Different dispatchers can be needed or execution result can be intercepted by view model. Or even executions can be chained.</p><p>This library mostly reduces these case codes to one line. By doing this it respects clean architecture rules. Besides library’s presentation layer written as interface extension functions. So you can use them without your parent classes.</p><p>Library consists of 4 modules: dataholder, cabdata, cabdomain and cabpresentation. “CAB” prefix is short version of “Clean App Base”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*3iNNl2OcknvTA81sEukrfw.png" /><figcaption>Library modules</figcaption></figure><p>So we can dive in module by module</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FSiKqNZqksVYWmQEMjd%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FSiKqNZqksVYWmQEMjd%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcmZsdWV0Mmx4dDdiNmd2ZnFwOXR4a3Fzang2MWZ0MHgyenh1dmF1MyZlcD12MV9naWZzX2dpZklkJmN0PWc%2FSiKqNZqksVYWmQEMjd%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dabe140e1ce93a1631f44a4a9bf74f1/href">https://medium.com/media/4dabe140e1ce93a1631f44a4a9bf74f1/href</a></iframe><h3>1- Dataholder Module</h3><p>Actually it must belong to domain module but it can be used in other projects that doesn’t use clean app base library. This module is seperated because of the distribution reasons. Domain module uses this module as ‘api’ so projects that use clean app base domain module doesn’t require to add it separately.</p><p>It contains <strong>DataHolder&lt;T&gt;</strong> class and it’s extensions. Also defines a base error that <strong>DataHolder&lt;T&gt;</strong> has it as a variable. Apps can extend this base error and handle it in necessary places.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d85982b74e73d048d25357f35cd3109c/href">https://medium.com/media/d85982b74e73d048d25357f35cd3109c/href</a></iframe><p><strong>DataHolder&lt;T&gt;</strong> class is a sealed generic class. It means that <strong>DataHolder&lt;T&gt;</strong> class can be used as only <strong>DataHolder.Success&lt;T&gt;</strong>, <strong>DataHolder.Fail</strong> and <strong>DataHolder.Loading</strong>. This mechanism provides us to carry data in the app in a standard way. It indicates data state(Success, Fail and Loading) and can contain data according to its type. Let’s examine this types:</p><h4>DataHolder.Success&lt;T&gt;</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87237fd2944d04359908ddde106b3a2e/href">https://medium.com/media/87237fd2944d04359908ddde106b3a2e/href</a></iframe><p>This state tells us that getting data is successful and we have the data. This class gets its data type from base class(<strong>DataHolder&lt;T&gt;</strong>). It has a data:T variable that is not nullable. Making this variable nullable would require null check everywhere that it is used and this makes code crowded. This data can be used as nullable data with a wrapper like class TWrapper(val t: T?)in <strong>DataHolder&lt;TWrapper&gt;</strong></p><h4>DataHolder.Fail</h4><p>This state indicates that returned data failed with or without a reason. It has errorResourceId and errStr variables to show error with a message. And has a BaseError class that can be used as base class for any type of error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e5fd85b565d58068d993239c35f9793/href">https://medium.com/media/9e5fd85b565d58068d993239c35f9793/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7de6525c3e23e193403ee8457d422c28/href">https://medium.com/media/7de6525c3e23e193403ee8457d422c28/href</a></iframe><h4>DataHolder.Loading</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o7bu8sRnYpTOG1p8k%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o7bu8sRnYpTOG1p8k%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3o7bu8sRnYpTOG1p8k%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4af7abc4bee649045e21a1d2927de06/href">https://medium.com/media/d4af7abc4bee649045e21a1d2927de06/href</a></iframe><p>Making a mobile app 99% would require a long running task. Long means making users: “Bruh… this app is freezing ”. So almost every platform shows a loading indicator to the user while executing long running tasks. If our <strong>DataHolder&lt;T&gt;</strong> type is <strong>DataHolder.Loading</strong> tells us to show that: “I’m just waiting for the result, don’t think I’m freezed dude!” to the user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77d82287caa3078a4148919cf515173c/href">https://medium.com/media/77d82287caa3078a4148919cf515173c/href</a></iframe><p>It has loadingResourceId and loadingStr fields to show a message to the user while loading. Has a cancellable property for determining whether user can cancel execution or not. Progress indicates progress of execution between 0–100 and tag to identify executions and trigger a callback to executor classes.</p><h4>HandleSuccess Extension</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e2800c27225b15f929081d89fbae861/href">https://medium.com/media/1e2800c27225b15f929081d89fbae861/href</a></iframe><p>Most of the time data flow is intercepted. For example, repository maps enterprise models to the app models. Without extension you must check all types of <strong>DataHolder&lt;T&gt;</strong> in a whenstructure. And the operation is meaningful only if it is <strong>DataHolder.Success</strong>. So it generates boilerplate code. With the extension you can operate your function in one-line code.</p><h3>2- Data Module</h3><p>This module defines base classes for the app’s data layer. <strong>DataSource</strong>, <strong>ApiCallAdapter </strong>and <strong>BaseResponse </strong>are the classes. Last two are base for network connections, designed for Retrofit 2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a1816433ddd14aaa2a7c97ea1a37093/href">https://medium.com/media/3a1816433ddd14aaa2a7c97ea1a37093/href</a></iframe><p>ApiCallAdapter takes a lambda function as a parameter and returns a <strong>BaseApiResponse&lt;T&gt;. </strong>The app should implement it’s api response that extends <strong>BaseApiResponse&lt;T&gt; </strong>according to backend result model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c79690c6eedceb3a1ddf3e224dae36d/href">https://medium.com/media/8c79690c6eedceb3a1ddf3e224dae36d/href</a></iframe><p>DataSource is the base for all data sources in the app. It has two types that contain two methods. Async data source’s methods are <strong>suspend </strong>functions while Sync data source is not. So that sync data source can be used to get data directly from RAM (it is safe to use in the main thread) or simple calculations. Async data source functions can be called from another suspend function or coroutine.</p><p>Fetch prefix means get data without a parameter. Request prefix means getting data needs a parameter. These parameters and returned models are usually enterprise objects, for example: ProfileNetworkDTO, ProfileLocalDBDTO and ProfileRequestNetworkDTO.</p><h3>3- Domain Module</h3><p>Domain module only contains the Interactor interface. Actually this is the place of <strong>DataHolder</strong> but it is moved to another module because of the distribution reasons. Still it provides DataHolder by including it as api instead of implementation. Here is the Interactor interface:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d7b79d03e7ae23aae5e14a87885d3ce/href">https://medium.com/media/3d7b79d03e7ae23aae5e14a87885d3ce/href</a></iframe><p>Yes, there are a lot of interfaces, but logic is simple. They are generated according to return type(<strong>DataHolder&lt;T&gt;</strong> or <strong>T</strong>), being suspend fun or not and taking a parameter. They all have an execute method that does work. Most used interfaces are:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec934eedc7471a8b8c2bba83c8d27ccc/href">https://medium.com/media/ec934eedc7471a8b8c2bba83c8d27ccc/href</a></iframe><p>With these, we can get our data in a coroutine or another suspend function and get data in <strong>DataHolder&lt;T&gt;</strong> wrapper. Retrieve means there is no need to a parameter to request data. Speaking of parameter, it has an important role at separating data and presentation layers. Parameter of <strong>SingleInteractor</strong> is a subclass of <strong>Interactor.Params</strong> class. By this way parameters of Interactor is wrapped and any change in parameters can be arranged from this wrapper. In the next part of this series there will be examples to usage of these <strong>Interactors</strong>.</p><h3>4- Presentation Module</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxT9IgDVYZrFS1hv9ok%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxT9IgDVYZrFS1hv9ok%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FxT9IgDVYZrFS1hv9ok%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="319" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba15dd0d74a40f26c32b77db2c3d10a0/href">https://medium.com/media/ba15dd0d74a40f26c32b77db2c3d10a0/href</a></iframe><p>This module contains interfaces for ui elements, extensions for these interfaces and some helper classes. Interfaces are mostly used to tag ui elements for using them at the other parts of the library and use extension functions for ui elements. Extension functions do actual job for this layer. They handle executing interactor, observing them and take action according to DataHolder state. So let’s see them in detail.</p><h4>Interfaces</h4><p>Why interfaces? Because I want developers to use this library without changing their base classes. As you know a class can be extended from multiple interfaces. I put all logic in interface extensions so it can be used with a minimal change of user class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*wINavSdH0dXEs5szFOU5xw.png" /></figure><p>CAB means Clean Application Base. SAP means Simple Animation Popup which is an animation library included in the presentation module.</p><p><a href="https://github.com/alperenbabagil/simpleanimationpopup">alperenbabagil/simpleanimationpopup</a></p><p>In async programming, it is important to show the user the current state(Loading, Success and Fail). In my library this is done by dialogs or give the library implementer class a signal about current state. Users can choose to use built-in dialogs in the library. If so, <strong>CAPSAPActivity</strong> or <strong>CAPSAPFragment</strong> interfaces must be used. Otherwise <strong>CAPActivity</strong> or <strong>CAPFragment</strong> must be used. These interfaces have state callbacks which must be handled by the developer. I used <strong>CAPSAPXXX </strong>interfaces in the demo project. Let’s look inside of <strong>CAPSAPActivity </strong>interface:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09872eb7a31e159ba14a9e4a251ceef0/href">https://medium.com/media/09872eb7a31e159ba14a9e4a251ceef0/href</a></iframe><p>Yes, there is no method in interface. It is just for use extensions and recognized by other classes. It has two extension methods: handleDataHolderResult() and observeDataHolder().First method takes action according to <strong>DataHolder</strong>’s state. If it is <strong>DataHolder.Loading</strong> calls showDHLoadingDialog() function of <strong>DialogHolderInterface</strong>. It helps to showing a loading indicator dialog with notifying view model when is cancelled. It is usefull when we want to stop a specified interactor execution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b157189c391105a0555f1e5b5cbdb4cc/href">https://medium.com/media/b157189c391105a0555f1e5b5cbdb4cc/href</a></iframe><p>This is actually a classic <strong>SAP</strong> loading action but when dialog is cancelled it notifies cabViewModel of <strong>DialogHolderActivity</strong>. I will explain it at the <strong>CABViewModel</strong> section.</p><p>When the result data holder’s state is <strong>DataHolder.Fail </strong>it dismisses current dialog. if bypassErrorHandling parameter is true errorBody callback is invoked with the error messages. If it is false an error dialog presented with error messages and error dialog button click callback.</p><p>When the result data holder’s state is <strong>DataHolder.Success </strong>it invokes successBody callback with DataHolder.data. Before that if bypassDisableCurrentPopupOnSucces parameter is true current dialog is not dismissed. It is useful when chaining observations. Otherwise the current dialog is dismissed. Here current dialog is most probably a loading dialog.</p><p>Usage is mostly the same in CABSAPFragment interface too. It just looks for CABSAPActivity as fragment holder to show dialogs.</p><p>When it comes to view model there is <strong>CABViewModel</strong>. It needs child class to implement val jobMap : HashMap&lt;String, Job&gt;. It is used to keep track of executing <strong>Interactor</strong>s in a coroutine. When an execution is completed or cancelled they are removed from the list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e1a9afe58cc75bd1c879da4f4a4ab4a/href">https://medium.com/media/7e1a9afe58cc75bd1c879da4f4a4ab4a/href</a></iframe><p>It has execInteractor() extension functions for <strong>SingleInteractor</strong> and <strong>SingleRetrieveInteractor</strong>. These functions handle all the execution logic for us with various parameters. They do basically set the value <strong>of MutableData&lt;DataHolder&lt;T&gt;&gt;</strong> instance state to <strong>DataHolder.Loading</strong> in a coroutine, then set result to this instance when execution finishes. When this live data is observed in <strong>CABActivity</strong> or <strong>CABFragment</strong> in observeDataHolder() function appropriate dialogs and ux is provided to the user. Then the job is removed from the jobMap. Because the execution runs in viewModelScope it is safely executed. No need to consider life cycle events of Activity, Fragment or ViewModel.</p><p>The execution can be intercepted. It is useful when chaining executions or lookup to data before sending it to the observer. Even the result can be consumed in the view model. It is determined by interceptorBlock result. It is a lambda function that called when between execution finishes and passes the result to the observer. If it returns a true value, the result is not passed to the observer.</p><p>Additionally you can set cancellability of execution. It sets the loading dialog cancellable or not when presenting to the user. If you remember I mentioned that when an execution cancelled by the user view model gets notified. When loadingCancelled() function of this interface is called with a tag the job has the tag found in jobMap and cancelled safely. You can also set coroutine dispatcher for this execution. It is given as a parameter to execInteractor() methods.</p><p>Finally there are some view extensions to simplify controlling of views.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15a3c443e7da6e5ed35aaa63e339043e/href">https://medium.com/media/15a3c443e7da6e5ed35aaa63e339043e/href</a></iframe><p>show() and hide() arrange view visibility. setVisibility() is useful when using databinding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*H4jse15PNy8kkEenOUarcQ.png" /></figure><p>That was all for this chapter. In the next chapter I’ll be talking about demo app that uses this library and some Android concepts.</p><p>Happy coding 🎉</p><p><strong>Part III:</strong></p><p><a href="https://babagilalperen.medium.com/android-clean-app-base-library-clean-architecture-mvvm-part-iii-c35724fcd11f">Android Clean App Base Library (Clean Architecture + MVVM) — Part III</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4ab489838a8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/huawei-developers/android-clean-app-base-library-clean-architecture-mvvm-part-ii-e4ab489838a8">Android Clean App Base Library (Clean Architecture + MVVM) — Part II</a> was originally published in <a href="https://medium.com/huawei-developers">Huawei Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Clean App Base Library (Clean Architecture + MVVM) — Part III]]></title>
            <link>https://babagilalperen.medium.com/android-clean-app-base-library-clean-architecture-mvvm-part-iii-c35724fcd11f?source=rss-97ca014e3401------2</link>
            <guid isPermaLink="false">https://medium.com/p/c35724fcd11f</guid>
            <category><![CDATA[libraries]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[mvvm]]></category>
            <dc:creator><![CDATA[Alperen Babagil]]></dc:creator>
            <pubDate>Thu, 26 Nov 2020 21:17:47 GMT</pubDate>
            <atom:updated>2020-11-26T21:29:29.783Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/p/e4ab489838a8/edit?source=your_stories_page-------------------------------------">Android Clean App Base Library (Clean Architecture + MVVM) — Part III</a></h3><p>Hello everyone 🙋‍♂️ In this part I will show the demo app of Clean App Base Library.</p><p><a href="https://github.com/alperenbabagil/cleanappbase">alperenbabagil/cleanappbase</a></p><h4>What does this app?</h4><p>It gets users from a server and lists them. If any user clicked a detail page opened. In the detail page user details and editing profile picture implemented as two tabs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*nPmstS6e6kKVsgXbz2Z3lA.gif" /><figcaption>App usage</figcaption></figure><p>It uses <a href="https://fakejson.com/">Fakejson</a> as the data source. It is a really good tool to mock a server. It can respond how you want the answer or can respond built-in data or list.</p><h4>Structure</h4><p>It is an one-module app that consists of three packages. I named every package as an app feature. These are: core, detail and main. They are all divided by three familiar packages: data,domain and presentation. They are all connected with Koin dependency injection library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*YSDsc8tsCQvPh_mvcjkxXg.png" /><figcaption>App structure</figcaption></figure><p>core package includes app wide base classes ,network specifications and <strong>CABDemoApp</strong> class. detail package includes profile detail screens and features. main package includes main page screens and features. Let’s examine one by one:</p><h3>core</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*tJnZ97Oh_izRfHkUX_Gsbg.png" /><figcaption>core package</figcaption></figure><p>core package includes all app-specific base classes. When you completed the core package based of Clean Application Base library, development of features becomes very easy.</p><h4>core.data</h4><p>This package handles data layer base classes and models. Because of our data source is only network, it contains network classes mostly. It also has a base DataSource and ApiCallAdapter implementation.</p><p>Networking is an app-specific feature. Server addresses, server request-response types, authentications and sessions differ app to app. First of all I created server data models.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8dfbec9053179824665c9b630217bd1f/href">https://medium.com/media/8dfbec9053179824665c9b630217bd1f/href</a></iframe><p>There are some json request and response examples to understand better above structures:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2577362ef01adc4b0907c06b74addad1/href">https://medium.com/media/2577362ef01adc4b0907c06b74addad1/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24d9719e6327eae32f10ba27eb0a273a/href">https://medium.com/media/24d9719e6327eae32f10ba27eb0a273a/href</a></iframe><p>In the request: data, parameters and token sent to server. data is what we want from the server as a response data. parameters are api properties to manage how we want the data. token is required to get data from the api.</p><p>In the response: Only our data type is returned from the server.(<strong>ResponseTemplate&lt;T&gt;</strong>). Here T is <strong>ProfileDetail</strong> model which resides in detail package.</p><p>But how this data is processed?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F26DMVBP5MLkooJV28%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F26DMVBP5MLkooJV28%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F26DMVBP5MLkooJV28%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccfdb7c3091d38f8c6e308714d295bae/href">https://medium.com/media/ccfdb7c3091d38f8c6e308714d295bae/href</a></iframe><p>Converting server text data to our classes done by <strong>ApiCallAdapter. </strong>It is a base class for app specific implementations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90ca3ac338a72436e456bb63f2dce971/href">https://medium.com/media/90ca3ac338a72436e456bb63f2dce971/href</a></iframe><p>It takes a lambda function to handle service calls. The function returns a subclass of <strong>BaseApiResponse&lt;T&gt;</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c344acef11e9b1b329a3135d0b7a929f/href">https://medium.com/media/c344acef11e9b1b329a3135d0b7a929f/href</a></iframe><p>Here is the implementation of <strong>ApiCAllAdapter</strong>. It must be app specific because server responses and handling is different at every app.</p><p>It handles retrofit calls and produces a <strong>DataHolder&lt;T&gt;</strong> according to server statuses. It also handles error cases such as wrong response format, invalid token and no internet conditions. It executes response as a try,catch block, so there will be no runtime crash because of these errors.</p><p><strong>BaseDataSource</strong> is a app-specific base class for CAB <strong>DataSource</strong>. It can be used to intercept all data sources and modify them. It is not used to modify data for now but I added to demonstration purposes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc47f7e72e089d99b28a183f225cd0c5/href">https://medium.com/media/fc47f7e72e089d99b28a183f225cd0c5/href</a></iframe><p>It is a base for <strong>AsyncDataSource.RequestDataSource.</strong> It can also be implemented for other data source types.</p><h4>core.domain</h4><p>This package has Base Interactors and RequestResultType model. Again there is no need to create Base class for interactors. It is created for just demonstration purposes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1971ed6495a77a280be7621acbea63ab/href">https://medium.com/media/1971ed6495a77a280be7621acbea63ab/href</a></iframe><h4>core.presentation</h4><p>This package has base Activity, Fragment and ViewModel. Additionally it has navigation and UI helper classes. These component bases actually just implement the CAB library component interfaces. Let’s look at them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/781a0cfa077cde817dd760f1ed83113f/href">https://medium.com/media/781a0cfa077cde817dd760f1ed83113f/href</a></iframe><p>They are implemented the CAB library to prevent every feature component implementing it again and again. All feature components are childs of this package base component classes.</p><p><strong>Navigation</strong></p><p>Navigation is again an app-specific issue. You can use multi-activity, single-activity or hybrid navigation strategies. I used a navigation helper class to provide a simple navigation between activities. It has an Interface named <strong>NavigatorOwner</strong> that provides an <strong>AppNavigator</strong>. It is implemented by <strong>CABDemoBaseActivity</strong>, so every child activity will have this navigation helper class. The <strong>AppNavigator</strong> instance provided by the DI.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b8a44d8f057342c3ed3d79d251b5679/href">https://medium.com/media/3b8a44d8f057342c3ed3d79d251b5679/href</a></iframe><p>CAB library has a helper class named <strong>IntentLoader </strong>to navigate between modules by using activity’s full class name in modular projects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dbfc10cf4104b8580a4455044d66595/href">https://medium.com/media/1dbfc10cf4104b8580a4455044d66595/href</a></iframe><p>This package also contains <strong>CabDemoApp</strong> class. Again App class is an app-specific class so it must belong here. This class is needed to initialize DI.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1d61aa0b75cfea4bb92b2ebd7ca03be/href">https://medium.com/media/a1d61aa0b75cfea4bb92b2ebd7ca03be/href</a></iframe><p>core package has the main implementation code of CAB library.</p><p>We will continue with the feature packages, so I suggest taking a coffee break :)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3nbxypT20Ulmo%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3nbxypT20Ulmo%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3nbxypT20Ulmo%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="321" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfa7e0ea3fb789bab1c645329cfd1518/href">https://medium.com/media/dfa7e0ea3fb789bab1c645329cfd1518/href</a></iframe><p>Let’s look at feature packages to how CAB library properties is used via core package:</p><h3>main</h3><p>This package is responsible for showing the user list as a first screen. It must also navigate to detail screen when a row in list clicked. This package also has data, domain and presentation layers. When the user enter the app <strong>MainActivity</strong> opened. Then it shows a dialog using <strong>CABActivity</strong> extension methods. In the dialog user asked to choose get <strong>Fail</strong> or <strong>Succes</strong> data. If the user selects fail an error dialog is shown. Otherwise data is requested from the server and <strong>RecyclerView</strong> is populated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*pDXPTOnDr1BG3flyDuIqXA.png" /></figure><h4>main.data</h4><p>It has its own models, data sources, repository implementation and DI module. Everything related with the main data is implemented here. It moves data to the upper layer via repository. Let’s look at them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e37ca2b2d307c9e8463c36a78072c83/href">https://medium.com/media/9e37ca2b2d307c9e8463c36a78072c83/href</a></iframe><p>First class is the request model. We request a list model from api. This is usage of api’s person create feature. It creates a random person with requested properties.</p><p>Second class is a network data transfer object model. This model belongs to the data layer. It is an enterprise model so it must be converted to an app model which resides in the domain layer. This conversation is provided by mapToUserListItem() extension function. As you can see it converts the server date string to <strong>Date</strong> object in desired format. It also generates a working image url link from userId(personNickName).</p><p><strong>GetUsersDataSource</strong> is the data source implementation of main.data</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96e6ece35c57354e8bd006951a13a19e/href">https://medium.com/media/96e6ece35c57354e8bd006951a13a19e/href</a></iframe><p>It takes user service and <strong>ApiCallAdapter </strong>as variables. It just calls adapt function of <strong>ApiCAllAdapter</strong>. Its request type is <strong>ResponseTemplate&lt;UserListDataTemplate&gt;</strong> and return type is <strong>DataHolder&lt;List&lt;UserListItemNetworkDTO&gt;&gt;</strong></p><p><strong>UserService </strong>is an interface with a function annotated with Retrofit annotation. It actually gets data from the server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9aa765b2e01033bd593d209c42d86fd7/href">https://medium.com/media/9aa765b2e01033bd593d209c42d86fd7/href</a></iframe><p>It is a suspend function. That means it can be called from another suspend function. If you remember all functions are suspend functions up to viewModel in the call chain.</p><p><strong>ApiCall </strong>adapter is provided by DI at core.data package. It is provided as a Singleton object so all data sources use the same call adapter.</p><p>The final class to examine is <strong>UserRepositoryImpl</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7250c165a637af0f1c1b97cdf7e74f94/href">https://medium.com/media/7250c165a637af0f1c1b97cdf7e74f94/href</a></iframe><p>Repository is the place that the business logic must be implemented. DataSources are responsible for only getting data in the form of data layer models. Mixing data sources, filtering or transforming models are job of the repository. In this scenario the server returns a successful response if there is no other error. But we want to see error response from the server.(with our data types). So we provide a <strong>RequestTemplate&lt;UserListDataTemplate&gt;</strong> to the data source as parameter that what type of result we want. Then we put data to be returned from the server(<strong>UserListDataTemplate </strong>or <strong>Error)</strong>. Finally execute data source and return data mapped to<strong> List&lt;UserListItem&gt;</strong>, which is an application model if the execution result is<strong> DataHolder.Success</strong>. Otherwise return<strong> DataHolder</strong> to the interactor without intercepting.</p><p><strong>But how are they connected?</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxT5LMUeCoYH1DEGCys%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxT5LMUeCoYH1DEGCys%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FxT5LMUeCoYH1DEGCys%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="328" frameborder="0" scrolling="no"><a href="https://medium.com/media/28a551652b9baa3c333f1d01bbc3794e/href">https://medium.com/media/28a551652b9baa3c333f1d01bbc3794e/href</a></iframe><p>The answer is dependency injection. I defined all class creation definitions in <strong>MainDataModule</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/368c99a467500a3594e2ce9c88eb5759/href">https://medium.com/media/368c99a467500a3594e2ce9c88eb5759/href</a></iframe><p>factory{} means everytime the object requested create a new instance for it. By that way, the instance will be removed from memory when there is no reference to it. So they will not cause a memory leak after the user <strong>ViewModel</strong> is closed.</p><p>named&lt;T&gt; is used because there are other implementations of <strong>BaseDataSource</strong>. So we must tell to DI this: Give me a <strong>BaseDataSource</strong> but it must be <strong>GetUserDataSource</strong>. But why didn’t we requested <strong>GetUserDataSource</strong> directly? Because <strong>UserRepositoryImpl</strong> takes a constructor parameter type of <strong>BaseDataSource&lt;ResponseTemplate&lt;UserListDataTemplate&gt;,<br> List&lt;UserListItemNetworkDTO&gt;&gt;</strong>. So management of the DI is important if we don’t want to struggle with the runtime errors.</p><h4>main.domain</h4><p>This package has the application data model, interactor and the repository interface. Application data model has app or platform class type variables. So we can use it in the presentation layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/321a6cbad4724d9dd113981dc457ffd1/href">https://medium.com/media/321a6cbad4724d9dd113981dc457ffd1/href</a></iframe><p>Since our feature does one job(Getting user list) there is one interactor. Our interactor is <strong>GetUsersInteractor</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/776f253ac4a406269714d4e9357e90f9/href">https://medium.com/media/776f253ac4a406269714d4e9357e90f9/href</a></iframe><p>It takes a userRepository at the constructor. Its type is a generic type of <strong>BaseSingleInteractor&lt;GetUsersInteractor.Params,List&lt;UserListItem&gt;&gt;</strong></p><p><strong>Param</strong> is an interactor specific type. It provides separation of data and presentation layers.</p><p>It has an override function: executeInteractor(params:<strong>GetUsersInteractor.Params</strong>). User of this interactor must call only this function with the required parameters.</p><p><strong>main.presentation</strong></p><p>It consists of three classes: <strong>MainPresentationModule</strong>, <strong>MainActivity</strong> and <strong>MainViewModel</strong>. <strong>MainPresentationModule</strong> provides <strong>MainViewModel</strong> via Koin DI:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22637033e88b06517e9c55a1fdb5d1ae/href">https://medium.com/media/22637033e88b06517e9c55a1fdb5d1ae/href</a></iframe><p>It is binded to <strong>CABDemoBaseViewModel</strong> because <strong>DialogHolder</strong> expects <strong>CABDemoBaseActivity</strong>(which is the parent class of <strong>MainActivity</strong>) to provide a <strong>CABViewModel</strong>(which is the parent class of <strong>CABDemoBaseViewModel</strong>)</p><p><strong>MainViewModel</strong> executes the interactor and passes the result to a <strong>LiveData&lt;List&lt;UserListItem&gt;</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53f4c91c2ee6e405b0e41b9cb212a2cc/href">https://medium.com/media/53f4c91c2ee6e405b0e41b9cb212a2cc/href</a></iframe><p>It takes a <strong>Interactor.SingleInteractor&lt;GetUsersInteractor.Params,List&lt;UserListItem&gt;&gt; </strong>as a constructor parameter. Again it is not <strong>Interactor</strong> itself, it is base class. It gives a huge advantage to us when unit testing. It has _usersLiveData and usersLiveData. First one is a <strong>MutableLiveData</strong> to modify in the class. The other one is a <strong>LiveData</strong> to expose our live data to outside. We don’t want to our live data to be modified outside of this class.</p><p>To get users from api, getUsers() function is called. It just calls execInteractor() function of the <strong>CABViewModel</strong> extension. Under the hood, it makes _usersLiveData’s value to <strong>DataHolder.Loading</strong>. Then executes the interactor and posts result to _usersLiveData. Look for part 2 for further details.</p><p>In the <strong>MainActivity</strong>, this execution is triggered and results are observed. Let’s look inside it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23a3fbb8c0f4638ceedb05e4a3835d6f/href">https://medium.com/media/23a3fbb8c0f4638ceedb05e4a3835d6f/href</a></iframe><p>In <strong>MainActivity</strong> the user is asked to select the success or fail state of data that will be taken from the server via askForSuccessOrFail() function. It is asked in two places: In onStart() method and in button click callback of error dialog. Then according to state the data view model’s getUsers(requestResultType: <strong>RequestResultType</strong>) function is called.</p><p>In onCreate() function view model’s userLiveData is listened via observeDataHolder() extension function of <strong>SAPActivity</strong>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FUuGI8TFkruHoH0RTr2%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FUuGI8TFkruHoH0RTr2%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FUuGI8TFkruHoH0RTr2%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/832f358c12f1da9dc8c6e2b3a50ae75d/href">https://medium.com/media/832f358c12f1da9dc8c6e2b3a50ae75d/href</a></iframe><p>It basically manages dialogs according to live data state. Above code, it takes three parameters. First: liveData —<strong> LiveData</strong> to observe. Second: errorButtonClick — show error or success dialog to user again when error dialog button clicked. Third: successBody — fill recycler view when data holder result is success.</p><p>This is the end of <strong>main</strong> package.</p><p>The remaining package/feature is <strong>detail</strong> . It’s data and domain layers are mostly the same as main package. Since this part is quite long, I will show only one difference in the presentation layer. <strong>DetailActivity</strong> hosts 2 fragments: <strong>ProfileDetailFragment</strong> to show detail of selected profile and <strong>ChangePPFragment</strong> to edit selected user’s profile picture. These fragments are child classes of<strong> CABDemoBaseFragment</strong> that implements <strong>CABSAPFragment</strong>. Let’s look at <strong>ProfileDetailFragment</strong> as an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e7c5d33a188bfc2cdd24ab45039e0a8/href">https://medium.com/media/9e7c5d33a188bfc2cdd24ab45039e0a8/href</a></iframe><p>It has two buttons: Get Success and Get Fail. They call view model’s getProfileDetail() function with parameters that received from arguments. Then observes the view model’s profileDetailLiveData. If it’s state is success, fills the screen with the detail data. Implementation of <strong>CABSAPFragment</strong> is explained in start of this part.</p><p>This was part 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*KIvHlo0dv4zqABRVcRVfpA.png" /></figure><p>Happy coding! 🎉</p><p><strong>Part IV:</strong></p><p><a href="https://babagilalperen.medium.com/android-clean-app-base-library-clean-architecture-mvvm-part-iv-279cac41ada9">Android Clean App Base Library (Clean Architecture + MVVM) — Part IV</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c35724fcd11f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Clean App Base Library (Clean Architecture + MVVM) — Part IV]]></title>
            <link>https://babagilalperen.medium.com/android-clean-app-base-library-clean-architecture-mvvm-part-iv-279cac41ada9?source=rss-97ca014e3401------2</link>
            <guid isPermaLink="false">https://medium.com/p/279cac41ada9</guid>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[structure]]></category>
            <category><![CDATA[libraries]]></category>
            <dc:creator><![CDATA[Alperen Babagil]]></dc:creator>
            <pubDate>Thu, 26 Nov 2020 21:12:38 GMT</pubDate>
            <atom:updated>2020-11-26T21:27:51.782Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/p/c35724fcd11f/edit?source=your_stories_page-------------------------------------">Android Clean App Base Library (Clean Architecture + MVVM) — Part IV</a></h3><p>Hello everyone 🙋‍♂️ In this part I will show you some Android libraries that I used when implementing demo project. Also ,I will show you how I implemented unit testing.</p><p><a href="https://github.com/alperenbabagil/cleanappbase">alperenbabagil/cleanappbase</a></p><h3>Unit Testing</h3><p>This is one of the reasons why clean architecture is necessary. Clean architecture makes unit testing painless and easy. I’ve implemented unit test for both libraries and the demo app.</p><p>I use <a href="https://mockk.io/">Mockk</a> library because it goes well with Kotlin. Besides it gives us nice DSL functionalities to play with.</p><p>To make unit tests easier, I’ve followed 3 rules when writing the app code:</p><p><strong>1- Don’t make <em>Swiss Army Knife</em> Classes!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*poLuBbgdwl11QKLWjn355Q.jpeg" /></figure><p>Every class must implement only it’s responsibilities. For example a data source must only get the data. It shouldn’t have additional computing or persistence responsibilities. So in the project a lot of classes that consist of one function. Making them a unit makes unit testing easier.(Shocking!)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F57ZvMMkuBIVMlU88Yh%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F57ZvMMkuBIVMlU88Yh%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F57ZvMMkuBIVMlU88Yh%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="391" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8c0b2ac03d8e34f1ec3d49399a9d212/href">https://medium.com/media/b8c0b2ac03d8e34f1ec3d49399a9d212/href</a></iframe><p><strong>2- Impl Classes are None of Your Business. Take That Interface!</strong></p><p>When a class must be used by another class, the user class must know only what it needs. So our class must expose itself by implementing an interface. For example when repository using a data source it must only interest with the getting data. So it must just call the getData() function with the required parameters and expect the result from this call. Implementation of this DataSource interface or how it gets the data must be out of repository’s interest.</p><p><strong>3- Just Give My Instances (In the constructor if it’s possible)</strong></p><p>When a class must be used by another class, creation of this class must not be a part of the user class’s program logic. We have a pointy solution here: Dependency Injection. For example without DI when testing a view model’s one function that class creations must be part of this function: Interactor, Repository, DataSource and related Network Service. Additionally if it doesn’t get these instances as a parameter unit testing for this function makes no sense: Because it is not an unit anymore. Supply these dependencies via constructor is the clearest DI technique. When a class creation code is not reachable from application code, injecting a field to a class after it is created is also possible. For example an Activity can get its fields set by the DI mechanism.</p><h4><strong>Demo App Testing</strong></h4><h4><strong>core</strong></h4><p>In the core package, there is a heavy testing class for ApiCallAdapter implementation : CABDemoApiCallAdapterTest. Because there are too many possibilities when networking, all cases must be tested here.</p><p>We have only suspend fun &lt;T : Any&gt; adapt(serviceBody: suspend () -&gt; Response&lt;out BaseApiResponse&lt;T&gt;&gt;?)for this class. So we must give the service body that behaves how we want, and compare the result of this function call with the expected result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pPbDazpJlxFm-zC9t4ycXg.png" /><figcaption>Testing Success</figcaption></figure><p>First, I’ve created a serviceBody mock to manipulate using spyk(It is something between mock and real object). Then I’ve made it return a response that was defined at the start of the class. Then set my conditions such as: “every response.code() function call must return 200”. After setting all conditions, the mocked serviceBody is ready. Then our adapter’s adapt function is ready to be called. I’ve used run blocking because it is a suspend function. After calling the adapter and assigning it’s result to our expected variable, we must check if the result meets expectations. In line 76, the state of result is checked. In line 79, data of success data holder is compared with our expected data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iHUD9QbFkdA9r_1cP4ogEw.png" /><figcaption>Expected Instance</figcaption></figure><p>This test class goes like this. You can check all the cases that are tested at github repository.</p><p>Testing Retrofit</p><p>In order to manipulate Retrofit response I’ve used an Interceptor. Then got a response that behaves how I want:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7181d83e6536c6903a8bbeac09acb180/href">https://medium.com/media/7181d83e6536c6903a8bbeac09acb180/href</a></iframe><h4>main</h4><p>In the main package I’ve tested <strong>GetUsersDataSource</strong> and <strong>UserRepositoryImpl</strong> at the data layer, <strong>MainViewMoldel</strong> at the presentation layer.</p><p>In the<strong> GetUsersDataSourceTest </strong>class, two parameters are mocked<strong>: </strong>userService and apiCallAdapter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ov6w1u-8WfyHP8k8FFW7sg.png" /></figure><p>First apiCallAdapter is mocked and tested against desired results. Then userService is mocked and tested again. Because apiCallAdapter uses userService to get results, so manipulating userService affects apiCallAdapter’s result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHa2CFjS71MRsFTlt-705w.png" /><figcaption>Testing the adapter</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGqEe2kY6uthjRv9Tn9bPg.png" /><figcaption>Testing the adapter with the manipulated userService</figcaption></figure><p>In <strong>UserRepositoryImplTest </strong>class getUserDataSource parameter is mocked<strong>. </strong>Remember that they take interfaces as constructor parameters, not implementations. This saves us from generating mock classes with their needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PX1_42BffiISROmNFj3CGg.png" /><figcaption>Repository test</figcaption></figure><p>In line 59, our data source is manipulated to return <strong>DataHolder.Success</strong> and tested in line 67. Then results are checked at line 72 and 74.</p><p>In <strong>MainViewModelTest</strong> class, guess what is mocked: Yes, it is the getUsersInteractor: Only constructor parameter of <strong>MainViewModel</strong>.</p><p>This is one of the reasons why we use view models. It is not a context dependent structure(unless it is not an <strong>AndroidViewModel</strong>). So we can unit testing without running code in a device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T5pogJBm9XCTtW4d00V59Q.png" /><figcaption><strong>MainViewModel</strong> testing</figcaption></figure><p>In line 45, the interactor is manipulated. Then it is executed in line 54. In the view model our functions don’t return a value. Instead they post a value to a <strong>MutableLiveData</strong>. So we must check live data’s value after execution. But live data logic is asynchronous, so we must observe the live data. Live data is observed at line 52, then verified that it’s value is changed. Finally the result is compared at line 60 with the expected result.</p><h4>detail</h4><p>Detail page testing has nothing special. It is tested the same way with the main package.</p><p>This is the end of demo app testing. Let’s look at library testing:</p><h4>Library testing</h4><p>The library mostly consists of interfaces. So there is no need for many of these classes. So there is only one test class : <strong>CABViewModelKTTest</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c22257ab5d9dc497b8cb15e2a86f86f5/href">https://medium.com/media/c22257ab5d9dc497b8cb15e2a86f86f5/href</a></iframe><p>In this testing scenario, two extension functions of CABViewModel are tested. Both functions basically mock and execute the interactor, then compare results with the desired value.</p><h3>Extras</h3><p>In this part I want to show you some libraries/techniques that I used in demo app:</p><h4>Simple Animation Popup</h4><p>This a dialog library that I’ve used through the Clean App Base library. It reduces the code to show dialogs to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*qN6fa-l7brw_Xc3jy2JIqw.png" /></figure><p><a href="https://github.com/alperenbabagil/simpleanimationpopup">alperenbabagil/simpleanimationpopup</a></p><h4>Elements</h4><p>It is a useful library to use RecyclerView in your app. I’ve used it on the main screen of the demo app.</p><p><a href="https://github.com/natario1/Elements">natario1/Elements</a></p><h4>Coil</h4><p>This an image loading library for Android backed by Kotlin Coroutines.</p><p><a href="https://github.com/coil-kt/coil">GitHub - coil-kt/coil: Image loading for Android and Compose Multiplatform.</a></p><h4>Data Binding</h4><p>This an Android feature that helps to write reactive apps. I’ve used it when loading images from the web to an ImageView and writing a Date value to a TextView in XML code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5df9a663bc87f8a0724181e28ff15249/href">https://medium.com/media/5df9a663bc87f8a0724181e28ff15249/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2653cefb258b83360e314ee40dc39878/href">https://medium.com/media/2653cefb258b83360e314ee40dc39878/href</a></iframe><p>This is how I used DataBinding in the code. In the 3rd and 15th lines binding is used with the keys that are defined in binding extensions.</p><p>That’s all for the series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*hDQ4PLItxRGt_5tVHQcfOA.png" /></figure><p>Happy coding 🎉</p><p><strong>Part I:</strong></p><p><a href="https://babagilalperen.medium.com/android-clean-app-base-library-clean-architecture-mvvm-part-i-e8614978877f">Android Clean App Base Library (Clean Architecture + MVVM) - Part I</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=279cac41ada9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Release your Android library in modular way with Jitpack]]></title>
            <link>https://babagilalperen.medium.com/release-your-android-library-in-modular-way-with-jitpack-2f704be2aad3?source=rss-97ca014e3401------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f704be2aad3</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jitpack]]></category>
            <category><![CDATA[modular]]></category>
            <category><![CDATA[libraries]]></category>
            <dc:creator><![CDATA[Alperen Babagil]]></dc:creator>
            <pubDate>Wed, 23 Sep 2020 20:30:58 GMT</pubDate>
            <atom:updated>2020-09-23T20:30:58.539Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone 🙋‍♂️ In this article I will give a little hint that can save you from angry hours and smashing your keyboard 😁 If your module cannot be found by gradle sync you are at the right article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*tdM169CDszDnr_vjONbEiA.png" /><figcaption>🤔</figcaption></figure><p>When you intend to publish your awesome library you may want to distribute of its one module as one library. For example if you are making a image loader library you may want seperate image filter features from main library. Or image transformation or image animation…</p><p>I will not write about publishing an Android library on Jitpack, if you are reading this you must know how to do it. But I’m dropping some links about it:</p><ul><li><a href="https://www.journaldev.com/19364/jitpack-publish-android-library">JitPack - Publish Your Android Library - JournalDev</a></li><li><a href="https://medium.com/@ome450901/publish-an-android-library-by-jitpack-a0342684cbd0">Publish an Android Library by JitPack</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FRYiZZprUNJw%3Fstart%3D1704%26feature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DRYiZZprUNJw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FRYiZZprUNJw%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/3cab9eb9dd46cb19b88a0bf8007c59bd/href">https://medium.com/media/3cab9eb9dd46cb19b88a0bf8007c59bd/href</a></iframe><h3>Get to the point</h3><p>First you must write this</p><pre>classpath &#39;com.github.dcendents:android-maven-gradle-plugin:2.0&#39;</pre><p>at the buildscript -&gt; dependencies section at the project level build.gradle file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2kkKaW4yJH7WlLC-H8RhKw.png" /><figcaption>Project level build.gradle file</figcaption></figure><p>You must enter this code to <strong><em>every</em> </strong>module’s build.gradle file.</p><pre>apply plugin: &#39;com.github.dcendents.android-maven&#39;<br>group = &#39;com.github.your_github_name&#39;</pre><p>Under the</p><pre>apply plugin: &#39;com.android.library&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*TXYyHFmlkkYaXnsyyiScXg.png" /><figcaption>One of the module build.gradle files</figcaption></figure><p>The key point is every module even “app” module.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxT5LMS6Wbb6j9ENbSE%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxT5LMS6Wbb6j9ENbSE%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FxT5LMS6Wbb6j9ENbSE%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/3821c06cc7f2539727c8a45d99472108/href">https://medium.com/media/3821c06cc7f2539727c8a45d99472108/href</a></iframe><p>After that jitpack recognizes your module name and you can use your module at other libraries as:</p><pre>implementation &#39;com.github.alperenbabagil.cleanappbase:cabdata:0.0.6&#39;</pre><p>In above code cleanappbase is the project that includes other modules and demo app. ‘cabdata’ is a module that we want to use only. Last point is you must use “.” instead of “:” before the project name. Only last two punctiation must be “:”</p><p>Happy coding 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f704be2aad3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Huawei Push Kit ile arama ekranı yapımı]]></title>
            <link>https://medium.com/huawei-developers-tr/huawei-push-kit-ile-arama-ekran%C4%B1-yap%C4%B1m%C4%B1-ee9bc29b4112?source=rss-97ca014e3401------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee9bc29b4112</guid>
            <category><![CDATA[hms]]></category>
            <category><![CDATA[huawei]]></category>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[pushkit]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alperen Babagil]]></dc:creator>
            <pubDate>Fri, 14 Aug 2020 11:03:06 GMT</pubDate>
            <atom:updated>2020-08-17T06:49:41.474Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*SwsLv7vJ6_OPp7oyu8Rb5A.jpeg" /></figure><p>Herkese merhaba arkadaşlar. Bu yazımda Huawei Push Kit kullanarak bir canlı arama uygulamasının çalma ekranının yapımını anlatacağım. Öncelikle HMS Push Kit’i uygulamanıza entegre etmeniz gerekiyor. Push Kit Data mesajı ve Notification mesajı olmak üzere 2 mesaj tipini desteklemektedir. Notification, sistemin uygulamanızın çalıştırmaya gerek duymadan Bildirim Merkezinde (NC) gösterdiği standart bildirimdir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*ypSlUotuzmoCJgUwKPcwZw.png" /><figcaption>Huawei Bildirim Merkezi</figcaption></figure><p>Data mesajı ise sistemin notification ile gelen datayı uygulamanıza göndermesidir. Bu durumda uygulamanız (process) ayağa kaldırılır ve az sonra anlatacağım notification receiver service içindeki bir fonksiyon çalıştırılır. Bu fonksiyon içinde gelen datayı parse ederek uygulamanızda bir özellik çalıştırabilir veya aşağıda anlatacağım gibi bir gelen arama ekranı (call screen) gösterebilirsiniz. Bu türde sistem otomatik olarak bir bildirim oluşturmaz. Biz bu bildirim türünü kullanacağız.</p><p>HMS Push Kit’i entegre etmek ve örnek bir bildirim yollamak için şu medium yazısından yararlanabilirsiniz:</p><p><a href="https://medium.com/huawei-developers-tr/huawei-push-kit-ve-android-notification-7bb247cb622f">Huawei Push Kit ve Android Notification</a></p><h4>HMS Send Api Data Yapısı</h4><p>Bildirimlerinizi kendi server kodunuz üzerinden yollamak için HMS Send Api kullanmalıyız (<a href="https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/https-send-api-0000001050986197-V5">https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/https-send-api-0000001050986197-V5</a>). Bu api’ı kullanırken data mesajı yollamak için json yapımız şöyle olmalıdır:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8024ead8dfe1e22cac88bfffc8bfd9c9/href">https://medium.com/media/8024ead8dfe1e22cac88bfffc8bfd9c9/href</a></iframe><h3>Notification Receiver Service</h3><p>Bildirim almak içinHmsMessageServicesınıfından türeyen bir alıcı servis sınıfınız olmalı. Daha sonra ise onMessageReceived(remoteMessage : RemoteMessage?) fonksiyonunu override etmelisiniz. Eğer remoteMessage.data kısmı dolu ise bu bir data mesajıdır ve parse edip gerekli aksiyonu almamız gerekir.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21eb0057f644805fa40e8fb463895bde/href">https://medium.com/media/21eb0057f644805fa40e8fb463895bde/href</a></iframe><p>Gelen datayı parse ettikten sonra gerekli parametrelerle birlikte istediğimiz ekranı açabiliriz. Data mesajının en sık kullanıldığı durumlardan biri olarak arama ekranını örnek vermek istedim. Senaryomuzda gelen datayı parse edip CallScreenActivity’i açacağız.</p><p>İlk aklınıza gelen bu fonksiyon içinde yeni bir Intent ile gerekli activity’i açmak ve ilgli ekranda ses,görüntü ve ilgili butonları göstermek ise doğru fakat eksik düşünüyorsunuz :) Ne yazık ki Android ekosistemi tamamen önceki versiyonlarla uyumlu sistem sürümlerine, tek bir cihaz üreticisine ve genel bir güç optimizasyonu stratejisine sahip değil. Dolayısıyla bunları çözmenin yollarından bahsedeceğim.</p><h4>1- Güç Optimizasyonu</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hbfIC9cM4R_bAbzDevasYw.png" /></figure><p>Android telefonlar gerek AOSP güç yönetimi gerekse telefon üreticilerinin bağımsız olarak oluşturdukları bir dizi kurala göre uygulamaları kısıtlayabiliyorlar. Hatta daha can sıkıcı olanı belli bir süre boyunca kullanılmayan uygulamaları direkt öldürüyorlar(force stop). Böyle olunca uygulamanız çalışması gerektiği gibi çalışmıyor ve kullanıcı uygulamanızı silebiliyor ve uygulama mağazasına kötü yorum, kötü puan bırakabiliyor.</p><p>Bu durumu çözmek için 2 seçeneğimiz var: Birincisi ayrı ayrı telefon üreticilerine başvurup kendi uygulamanızı beyaz listeye aldırmak. Bu işlemin oldukça yorucu ve başarıyla sonuçlanma ihtimalinin düşük olduğunu söyleyebilirim. İkinci seçenek ise kullanıcıdan sizin uygulamanız için güç optimizasyonu seçeneklerini devre dışı bırakmasını istemek. Burada da her markanın güç optimizasyonu ayarlar sayfasının farklı isimde olması ve ortalama bir kullanıcı için fazla karmaşık bir işlem olması sorunu yatıyor. İlk problemimizi tüm markaların güncel ayarlar sayfasını takip edip birkaç satır kodla bu sayfayı açan bir kütüphane sayesinde çözebiliyoruz(<a href="https://github.com/judemanutd/AutoStarter">https://github.com/judemanutd/AutoStarter</a>). İkincisi için ise örnek bir öğretici video veya slider koyularak sorun bir miktar çözülebilir.</p><h4>2- Service içinden Activity açma</h4><p>Android 10 ile birlikte kullanıcı deneyimini geliştirmek için ekran açıkken bir uygulamanın pat diye kendi Activity’sini açması engellendi. Bunun yerine bir Heads-up notification göstererek daha doğal bir kullanıcı deneyimi istendi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*WQtTqDOgVFmscOOp9pZ6sQ.jpeg" /><figcaption>Ekran açıkken çalan alarm. Alarm ekranı açılmadı.</figcaption></figure><p>Servisimizden Activity açmak için önce Android versiyon kontrolü yapmamız gerekiyor. Eğer 10 ve yukarısı ise bir bildirim göstermemiz ve NotificationCompat.Builder nesnemizin pending intentini ayarlarkensetFullScreenIntent(pendingIntent,true) böyle bir ayar yapmamız gerekiyor. Bu ayar eğer ekran kapalıysa Activity’nin açılmasını, degilse bildirime tıklandığında ilgili Activity’nin açılmasını sağlıyor. Bunun için ayrıca android.permission.USE_FULL_SCREEN_INTENT iznini de Manifest dosyasına yazmanız gerekiyor. Örnek bir bildirim gösterimi:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ee593eef86d288f5030c00304ca0c42/href">https://medium.com/media/6ee593eef86d288f5030c00304ca0c42/href</a></iframe><p>Android 10 altı cihazlar için ise normal olarak Activity’nizi başlatabilirsiniz. Yalnızca intente Intent.<strong>FLAG_ACTIVITY_NEW_TASK</strong> flag’ini eklemeniz gerekiyor. Ayrıca ekran kapalıyken ekran kilidini açmak için android.permission.WAKE_LOCK ve android.permission.DISABLE_KEYGUARD izninlerini de Manifest dosyasına eklemelisiniz.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee9bc29b4112" width="1" height="1" alt=""><hr><p><a href="https://medium.com/huawei-developers-tr/huawei-push-kit-ile-arama-ekran%C4%B1-yap%C4%B1m%C4%B1-ee9bc29b4112">Huawei Push Kit ile arama ekranı yapımı</a> was originally published in <a href="https://medium.com/huawei-developers-tr">Huawei Developers - Türkiye</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Yerel Tarih ve Saat Kullanımı]]></title>
            <link>https://babagilalperen.medium.com/android-yerel-tarih-ve-saat-kullan%C4%B1m%C4%B1-66e2a99c6a98?source=rss-97ca014e3401------2</link>
            <guid isPermaLink="false">https://medium.com/p/66e2a99c6a98</guid>
            <category><![CDATA[date]]></category>
            <category><![CDATA[datetime]]></category>
            <category><![CDATA[local]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[yerel]]></category>
            <dc:creator><![CDATA[Alperen Babagil]]></dc:creator>
            <pubDate>Wed, 20 Feb 2019 13:14:07 GMT</pubDate>
            <atom:updated>2019-02-20T13:14:07.757Z</atom:updated>
            <content:encoded><![CDATA[<p>Uygulamanızda tarih ve saati seçilen dil/bölge ayarlarına göre göstermek özellikle birden çok ülkede kullanılacaksa önemlidir. Örneğin Türkiye için tarih “Gün.Ay.Yıl Saat:Dakika” şeklinde kabul görmüşken Amerika için bu format “Ay/Gün/Yıl Saat:Dakika PM/AM” şeklindedir.</p><p>Elimizdeki <em>java.util.Date</em> nesnesini yerel formata çevirmek için <em>java.text.DateFormat</em> sınıfını kullanabiliriz. <em>DateFormat </em>nesnesini şu şekilde elde edebiliriz:</p><p>Tarih için:</p><pre>DateFormat dateFormatDate = android.text.format.DateFormat.<em>getDateFormat</em>(context) </pre><p>Saat için:</p><pre>DateFormat dateFormatTime = android.text.format.DateFormat.<em>getTimeFormat</em>(context) </pre><p>Sonraki adımda <em>dateFormatDate </em>ve <em>dateFormatTime </em>nesnelerinden <em>String</em> sonucu almamız gerekiyor:</p><pre>String dateStr = dateFormatDate.format(date); android.text.format.DateFormat.<em>getTimeFormat</em>(context)</pre><pre>String timeStr = dateFormatTime.format(date); android.text.format.DateFormat.<em>getTimeFormat</em>(context)</pre><p>Ondan sonra bu iki sonucu birleştirip aşağıdaki gibi kullanabilirsiniz:</p><pre>String localDateTimeString=dateStr+” “+timeStr</pre><p>Bunun sonucunda Türkçe ve İngilizce dili seçilmiş iki telefonun ekran görüntüsü şöyle olacaktır:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5DkxxU6keHpqp_Nm-Hq2uA.png" /></figure><p>İyi kodlamalar :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66e2a99c6a98" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>