<?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 Alexandr Minkin on Medium]]></title>
        <description><![CDATA[Stories by Alexandr Minkin on Medium]]></description>
        <link>https://medium.com/@rasalexman?source=rss-3d9c0162b5f9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*9U4KwofwZxlo_KElSTmLQA.jpeg</url>
            <title>Stories by Alexandr Minkin on Medium</title>
            <link>https://medium.com/@rasalexman?source=rss-3d9c0162b5f9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 21:02:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rasalexman/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[KOtlin Dependency Injection (KODI)]]></title>
            <link>https://rasalexman.medium.com/kotlin-dependency-injection-kodi-acf298f4f319?source=rss-3d9c0162b5f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/acf298f4f319</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Alexandr Minkin]]></dc:creator>
            <pubDate>Mon, 18 May 2020 16:54:49 GMT</pubDate>
            <atom:updated>2020-05-18T16:54:49.544Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4K9MaKYpjCuN1tegjqwOyg.jpeg" /></figure><p>Hello developers. Everybody now uses some <a href="https://en.wikipedia.org/wiki/Dependency_injection">dependency injection</a> into your project. Some of them have annotation processing some of them use kapt-plugin or reflection, but now I want to tell you how was written my own dependency injection framework with few lines of code and implementations. I wrote some DI-containers before with <a href="https://github.com/Rasalexman/KotlinMVC">different</a> <a href="https://github.com/Rasalexman/ViamFramework">realizations</a> and I had used a lot of <em>“ready for production”</em> frameworks such as <a href="https://dagger.dev/">Dagger</a>, <a href="https://kodein.org/Kodein-DI/">Kodein</a>, <a href="https://github.com/InsertKoinIO/koin">Koin</a>, <a href="https://github.com/MichaelRocks/lightsaber">Lightsaber</a>, <a href="https://github.com/stephanenicolas/toothpick">Toothpick</a>, etc. But no one of them doesn’t satisfy my needs. And I think, what if I create my own cool <a href="https://en.wikipedia.org/wiki/Service_locator_pattern">Service Locator</a> realization by Kotlin language. This is how <a href="https://github.com/Rasalexman/KODI"><strong>KODI</strong></a><strong> </strong>was born. The first version has used the kotlin-reflection library and it was good. So I start to think about independent module without reflection with all Kotlin language features like <a href="https://kotlinlang.ru/docs/reference/functions.html"><em>infix</em></a><em> functions,</em><a href="https://kotlinlang.org/docs/reference/inline-classes.html"> <em>inline classes</em></a>, <a href="https://kotlinlang.org/docs/reference/extensions.html#extensions"><em>extensions</em></a>, and <a href="https://kotlinlang.org/docs/tutorials/kotlin-for-py/inheritance.html#delegation"><em>delegations</em></a>. Here will describe how I made this!</p><h3>API Syntaxis</h3><p>First of all, choose the right human syntax. I really love how Kodein names this, so I going to imitate its syntax. <br>bind&lt;Instance&gt;(tag: String?) at &quot;ScopeName&quot; with single { InstanceImplementation() } this is how you can create your instance binder to <a href="https://en.wikipedia.org/wiki/Dependency_injection">DI-container</a>. bind is an inline extension function that creates inline class KodiTagWrapper that holds a key for DI-reference. with is an another cool Kotlin feature called infix operator. And then it has three types of binding: single — mean that only <strong>one</strong> instance of an initialized class will be binded. It’s also a lazy function; provider — <strong>provide</strong> called function or object reference every time its executed; constant — for the constant values. You can bind instances into DI-graph by its class name like bind&lt;MyClass&gt; or by tag bindTag(“MyClassTag”) . To start to initialize binding into containers you need to be in the context of Kodi framework by calling kodi { } and start to declare bind functions into including lambda expressions. There is a simple example of how to do it below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf370cb3a058cd29d84aec0417830b87/href">https://medium.com/media/bf370cb3a058cd29d84aec0417830b87/href</a></iframe><p>Another one great feature is a <strong>SCOPES</strong> with key at, which tells the instance namespaces. By default, all dependencies have default scope, but you can specify it explicitly as a string constant, and retrieve it later in any part of your code with instance&lt;T&gt;(tag: String?, scope: String?) .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d87e174c22fb198814ce0516ccb1249/href">https://medium.com/media/2d87e174c22fb198814ce0516ccb1249/href</a></iframe><p>This all that you need to do to create a simple dependency graph. Moreover, it doesn’t matter what order you assign the dependencies to, they will all be injected lazily. It’s can be done in MainApplication class or KodiModule, which I’ll tell you more about it later.</p><h3>Injection Methods</h3><p>As I said earlier, the KODI does not use any annotation processing or reflection library until version 1.4.+. Only pure Kotlin code. So this is so simple to inject your dependencies into target class. Just implement IKodi.kt interface to get all features of KODI injection. Next code snippet will show you how to inject your instances with delegation properties in Kotlin.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb4882c0ee61663a50abb1fdf10d6e35/href">https://medium.com/media/bb4882c0ee61663a50abb1fdf10d6e35/href</a></iframe><ol><li>- You can get an instance by lazy immutableInstance , that get value only for val property, which is a part of KODI Framework. Also, you can get mutableInstance for var . It’s always lazy read-write properties.</li><li>Directly get selected class to be injected into the property from DI-Container</li></ol><p>This is a really simple way to get all your dependencies in any part of your code.</p><h3>Kodi Modules</h3><p>Every big project has separated modules in it like domain-logic module or data module, or features modules, etc. KodiModules can help you to manage your project architecture in a <a href="https://www.amazon.com/Clean-Architecture-Craftsmans-Software-Structure/dp/0134494164"><strong>CLEAN</strong></a> way. There had been developed a great feature called KodiModule . This is a simple container for all of your bindings into the dependency graph. Every module can have <strong>SCOPE</strong> names too. So look at the example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e661f9fc5f207346617f142d9f202e30/href">https://medium.com/media/e661f9fc5f207346617f142d9f202e30/href</a></iframe><p>As you can see the way to create a module is to call high-order function kodiModule {…} and bind all necessary dependencies in it. Also, you can use the module scope name withScope “some_const_string” to specify a scope. It will automatically be added for all instances inside this module without inner <strong>SCOPE</strong> declarations with at keyword. Next step to add a module into your main project graph is to call import function,- kodi { import(systemModule) } declarations. Import can be used in another module that’s mean that we can combine modules with each other.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcffef1ec7c8c6847f3b2919a8969c1d/href">https://medium.com/media/dcffef1ec7c8c6847f3b2919a8969c1d/href</a></iframe><h3>AnnotationProcessing</h3><p>Next big thing in KODI that no one Kotlin dependency injection frameworks have (Koin &amp; Kodein), - is annotation processing with kapt. There are a few annotations that exist in KODI framework that can generate modules for you: @BindSingle, @BindProvider, @IgnoreInstance, @WithInstance</p><p>@BindSingle and @BindProvider works only with classes(statics and singletons) and methods (abstract and high-order) to automatically generate bind&lt;T&gt;() methods into modules with holder methods like single{} and provider{}. IgnoreInstance and WithInstance work properties and method params. @IgnoreInstance the annotation will ignore some instances to inject into your module binding. Using @WithInstance annotation you can specify what type of instance you want to inject into field or property. You need to implement kodigen library for <a href="https://kotlinlang.ru/docs/reference/kapt.html"><strong>kapt</strong></a> annotation processing. Let’s look at the example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc9097adfd0f6f4e65d169530717fb36/href">https://medium.com/media/dc9097adfd0f6f4e65d169530717fb36/href</a></iframe><p>No boilerplate code anymore. It also reduces the chance of making a mistake if your dependencies and their input parameters change or are removed in the future. We can use annotations with <a href="https://kotlinlang.ru/docs/reference/object-declarations.html">Kotlin singleton </a><a href="https://kotlinlang.ru/docs/reference/object-declarations.html">object</a> methods and <a href="https://kotlinlang.ru/docs/reference/lambdas.html">higher-order functions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/678851b8eabe3e7c456adc4f78cd8fca/href">https://medium.com/media/678851b8eabe3e7c456adc4f78cd8fca/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0231ab5145870d2c96287796a163251/href">https://medium.com/media/c0231ab5145870d2c96287796a163251/href</a></iframe><p>You can use abstract methods, companion object methods and interface methods for binding injections into the dependency graph. Here was a simple example of how to use this framework and you can find a full documented code into my <a href="https://github.com/Rasalexman/KODI">repository</a> with an example of usage in the typical android application. It’s been over 2 years since the first version of this framework was released. Now I have three modules in the project: <br>- kodi. This is the main <strong>core</strong> framework module, which contains base abstractions, implementations, and annotations.<br>- androidX. This module was created only for usage in <strong>android</strong> development. It contains all services that android framework has used since version SDK 14.<br>- kodigen. Module for <strong>generating</strong> code via annotation processing for KodiModules.<br>- kodireflect. Old legacy module created for use with Kotlin <strong>reflection</strong> without any bindings and have less boilerplate code style.</p><p>KODI is a constantly growing library with simple usage syntaxis. Just add an implementation to your project and try it out:<br>implementation &#39;com.rasalexman.kodi:kodi:x.y.z&#39;</p><p>and for annotation processing use:<br>kapt &#39;com.rasalexman.kodigen:kodigen:x.y.z&#39;</p><h4>Thanks for reading this article. Make some claps if you like it and please support me on github. Have a good day and write a clean readable code :)</h4><p><a href="https://github.com/Rasalexman/KODI">Rasalexman/KODI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acf298f4f319" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Paging Flow with Retrofit]]></title>
            <link>https://rasalexman.medium.com/paging-flow-with-retrofit-4fb069599044?source=rss-3d9c0162b5f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fb069599044</guid>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[pagination]]></category>
            <dc:creator><![CDATA[Alexandr Minkin]]></dc:creator>
            <pubDate>Sun, 19 Jan 2020 01:28:53 GMT</pubDate>
            <atom:updated>2020-01-19T01:33:09.590Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cEwldGyC3uJ0ZOhGavkVgA.jpeg" /><figcaption>Flow like a water</figcaption></figure><p>Since <a href="https://kotlinlang.org/docs/reference/coroutines/flow.html">Kotlin Flow</a> was release at version <strong>1.3.0</strong> there is a lot of articles about it from <a href="https://medium.com/@elizarov/kotlin-flows-and-coroutines-256260fb3bdb">Roman Elizarov</a>. Here I&#39;ll show you how it can easily make paging requests using <a href="https://square.github.io/retrofit/">Retrofit</a>, <a href="https://developer.android.com/topic/libraries/architecture/livedata">LiveData</a>, and modern Kotlin coroutines API under <a href="https://developer.android.com/jetpack/docs/guide">MVVM</a> Pattern. Someone can tell why you need this cause we already have a <a href="https://developer.android.com/topic/libraries/architecture/paging">Paging Library from JetPack</a>. But it’s not a silver bullet for whole your needs. Flow keeps it simple and Retrofit will help us to achieve this. But let’s start to see a classical paging approach. Typically you create a ViewModel with some LiveData who store and manipulate with paging event coming from UI controller, like Fragment or Activity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7eec4c03db9cf332189d928a7532b93d/href">https://medium.com/media/7eec4c03db9cf332189d928a7532b93d/href</a></iframe><p>This is some basic example. We use switchMap with eventLiveData to get the current ViewEvent&lt;Int&gt; with the page number from RecyclerView.OnScrollListener implementation. (i hope you have one :)<br>Then we call the function from the repository to get the next page. What is the problem here?! Every time when an event is fired we need to create liveData object that emits another call of the repository object and return Result&lt;List&lt;MyUIModel&gt;&gt; . Here and next, I’m using a standard Kotlin library class kotlin.Result&lt;T&gt; to simplify the responding state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e6486c421a10d3311d14770c59676df/href">https://medium.com/media/9e6486c421a10d3311d14770c59676df/href</a></iframe><p>Let’s see how this can be done with Kotlin Flow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a0e42e078b5f915a00e8657fd12c8f1/href">https://medium.com/media/2a0e42e078b5f915a00e8657fd12c8f1/href</a></iframe><p>The only difference here is that pagesRepository::getNextPageData now return Flow object and then we convert it to LiveData object by calling <a href="https://developer.android.com/reference/kotlin/androidx/lifecycle/package-summary#aslivedata">asLiveData()</a> . As you can see eventPageLiveData passing to the repository method. Now we create LiveData object only once and our repository abstraction looks like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e0f6b3db34faaa7b06bc55d35071e50/href">https://medium.com/media/5e0f6b3db34faaa7b06bc55d35071e50/href</a></iframe><p>Looks good. Some interesting thing coming out right now. It’s an implementation of the repository with only one method getNextPageData . I love to use Retrofit library cause it is simple and very easy to use in regular work. There is no implementation of <a href="https://developer.android.com/training/dependency-injection/manual">RemoteDataSource</a> , just only an example of API interface that used for making calls into the network</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7232647733d20c2a29cb109386ea5e33/href">https://medium.com/media/7232647733d20c2a29cb109386ea5e33/href</a></iframe><p>Since Retrofit version 2.6.0 we can use suspend keyword to connect it with coroutines Flow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bea0c80ac30740b44a5584d4ca81af08/href">https://medium.com/media/bea0c80ac30740b44a5584d4ca81af08/href</a></iframe><p>What is happens here? New <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/"><strong>Flow Builder</strong></a> instance was created andeventPageLiveData was converted to Flow with extension function <a href="https://developer.android.com/reference/kotlin/androidx/lifecycle/LiveData">LiveData&lt;T&gt;.asFlow()</a> . Then used <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/collect.html">collect</a>{...} function to retrieve ViewEvent&lt;Int&gt; data value and make the request to network API with suspending function simpleApi.getListData(page) from ISimpleApi implementation. Also, we catch the exceptions with <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/catch.html">catch</a>{...} function and switch thread to IO with <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flow-on.html">flowOn</a>(...) . Simple and easy ;)<br>I forgot one thing here it’s a converting “Remote Data Objects” to “UI Data Objects”. So we can make it like that</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42101ad8a5463550137626521dd3e44f/href">https://medium.com/media/42101ad8a5463550137626521dd3e44f/href</a></iframe><p>But I’m strongly recommended <strong>don’t do this</strong> on Presentation Layer. The better place to do that is Domain Layer with some additional business logic. In this article, I have omitted the implementation of this Domain Layer to simplify the example.</p><p>The next big question is — “Can we pass the Flow&lt;ViewEvent&lt;Int&gt;&gt; as page changing object into the repository?” And the answer is <strong>YES</strong>. We need to use <a href="https://kotlinlang.org/docs/reference/coroutines/channels.html">kotlinx.coroutines.channels.Channel&lt;E&gt;</a> and convert it to Flow with channel.<a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/consume-as-flow.html">consumeAsFlow</a>() for passing it to the repository function without converting LiveData.asFlow() . So it’s just another story ;)</p><h3>Conclusion</h3><p>In this article, you learned how easily we can use new Kotlin coroutines Flow to create simple paging request with Retrofit. Also, you learn about converting LiveData to Flow and vice versa. You can check the full example in my public repository on GitHub with a lot of code about using MVVM and modern programming libraries like <a href="https://developer.android.com/topic/libraries/data-binding">DataBinding</a>, <a href="https://developer.android.com/topic/libraries/architecture/paging">PagingLibrary</a>, <a href="https://developer.android.com/guide/navigation/navigation-getting-started">Navigation Component</a> and many more. Thanks for reading this story, have a good coding with passion and be in Flow like water. Please, make a <strong>CLAP</strong> for simple support!</p><blockquote>“You must be shapeless, formless, like water. When you pour water in a cup, it becomes the cup. When you pour water in a bottle, it becomes the bottle. When you pour water in a teapot, it becomes the teapot. Water can drip and it can crash. Become like water my friend.” — Bruce Lee</blockquote><p><a href="https://github.com/Rasalexman/PureMVVM">Rasalexman/PureMVVM</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fb069599044" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Builder Pattern by literal functions]]></title>
            <link>https://rasalexman.medium.com/builder-pattern-by-literal-functions-fa498ec7268?source=rss-3d9c0162b5f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa498ec7268</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[builder-pattern]]></category>
            <category><![CDATA[kotlin-extension]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alexandr Minkin]]></dc:creator>
            <pubDate>Tue, 27 Aug 2019 22:20:35 GMT</pubDate>
            <atom:updated>2019-08-28T15:59:18.890Z</atom:updated>
            <content:encoded><![CDATA[<h4>build objects with steroids in Kotlin</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*2QizMmTLK6JVZsTM0YZjeA.png" /></figure><p>Everybody knows about <a href="https://en.wikipedia.org/wiki/Domain-specific_language">DSL (Domain Specific Language)</a>. In this article, we will have a deeper look at it and see how to create an anonymous immutable data object from interfaces using Kotlin <em>literal functions with receiver</em> and <a href="https://en.wikipedia.org/wiki/Builder_pattern">Builder Pattern</a>.</p><h3>Literal function with receiver</h3><p>Literal function with receiver is A.(D)-&gt;C — a lambda ()-&gt;C that contains the context of the calling class A. <em>(receiver)</em> may also contain parameters D passed to it. They are similar to extension functions but with slight differences in syntax notation. Let’s look at the example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26c763d354e9b5aaa08dc891f7644420/href">https://medium.com/media/26c763d354e9b5aaa08dc891f7644420/href</a></iframe><p>Here typealias SingleLiteral = SingleClass.(String) -&gt; Unit a current type of literal function that takes an instance of SingleClass and hold it into lambda (String)-&gt;Unit . Inside the body of the function literal, the receiver object passed to a call becomes an <em>implicit</em> this, so we can access the members of that receiver object without any additional qualifiers, or access the receiver object using a <a href="https://kotlinlang.org/docs/reference/this-expressions.html">this expression</a>. We can take an additional parameter in lambda function by calling it . The main benefit of it is the ability to store the reference to the literal function in some variableval singleLiteral: SingleLiteral = { input -&gt; } and call it later singleClassInstance.singleLiteral(“Hello programmer”) . Function literals with receiver are often used in combination with higher-order functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f53844b51aa9ec7569cebb04a4dda22/href">https://medium.com/media/8f53844b51aa9ec7569cebb04a4dda22/href</a></iframe><p>with , apply , run is a literal functions with reciever in standard Kotlin stdlib library.</p><h3>Builder Pattern</h3><p><strong>DLS</strong> is based on <a href="https://en.wikipedia.org/wiki/Builder_pattern"><strong><em>Builder Pattern</em></strong></a> itself. In this chapter will be shown how to create and use it to build objects in different ways. Here we will consider the creation of User.kt and UserAddress.kt as an immutable anonymous object from its implementation of the interfaces</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d22b5c4b704b15a996c678cabdf39be5/href">https://medium.com/media/d22b5c4b704b15a996c678cabdf39be5/href</a></iframe><p>Then for creating an object, we could use a <em>DSL</em> to make it simpler:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*Vyqp79kf402zxnMLXgHPXg.png" /></figure><p>Our userInstance stays implementation of interface User with immutable properties. This looks simple and intuitive. It allows to control the way how objects will be created. In the function below you’ll see the realization of user and helper function init</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e68fdeb61faf243773f93d6dd21d2328/href">https://medium.com/media/e68fdeb61faf243773f93d6dd21d2328/href</a></iframe><p>This is a simple <em>inline</em> functions. As you can see it takes <em>literal functions with reciever</em> as a parameter. inline fun user takes parameter creator marked as noinline , cause we don’t want to use <em>inline</em> in ‘inner’ parameters. The initClass function takes an object of the created class T and applies a literal function init:T.()-&gt;R to it, passing the context of the applied class into it. Let’s look at the UserBuilder.kt first</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22816f0678853b71a9a0a1746dff6d4e/href">https://medium.com/media/22816f0678853b71a9a0a1746dff6d4e/href</a></iframe><p>This is all builder class. It only takes all necessary properties and builds complex properties like UserAddress.kt . It’s just a holder for our object implementation, thanks to him, we can make our objects immutable and not optional to apply default values to it. The second part of our builder is an <a href="https://kotlinlang.org/docs/reference/extensions.html#extension-functions">extension function</a>, which allows us to create our objects as well as their children. Let’s look at it more closely.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95fc75b50d52dbef94bc101446c27776/href">https://medium.com/media/95fc75b50d52dbef94bc101446c27776/href</a></iframe><p>This extension function is marked as <a href="https://kotlinlang.org/docs/reference/inline-functions.html">inline</a>, which means it will be built-in to the program text where its call will be made. A generic parameter T:User marked with the keyword <a href="https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters">reified</a> as a parameter of a real type. It is available inside a function in much the same way as a regular class. Since the function is inline, for the operation of such as, is and when reflection is not needed.<br>1. — using when expression, we can list all the possible types of generics of the parameter T <br>2. — we compare all types that we can create and describe how these types should be created. Here UserImpl.kt is a <em>class</em> or <em>data class</em> implementation of User.kt<br>3. — otherwise, we create an anonymous class, with the necessary fields, which inherit from our base interface.<br>Thus, we can get all the objects that will be immutable and are inheritors of the same type.</p><p>I propose to consider another implementation, through the inheritance of the builder class from lambda. It’s a UserAddress.kt builder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*BfnfolseRku96A-mwa7YNA.png" /></figure><p>The same literal function as input, but another realization of builder object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd1b48859b306baec3a6262b3775d804/href">https://medium.com/media/bd1b48859b306baec3a6262b3775d804/href</a></iframe><ol><li>First of all, used typealias, as another interesting feature of the Kotlin language, in order to simplify the expression of lambda ()-&gt;UserAddress</li><li>As a result, we can extend the lambda function as a regular class by using <a href="https://kotlinlang.org/docs/reference/type-aliases.html">typealias</a> . Simple right?!)</li><li>Next, call the parameter passed to the constructor with a literal function, like this.addressInit()</li><li>In the end, must definitely override the invoke method to call our class and assemble the object of UserAddress</li></ol><h3>Conclusion</h3><p>This article described what are <em>literal functions with receiver</em>, and how it can be applied in practice using the example of the <strong>Builder Pattern</strong>. It was also examined how to create immutable objects via interfaces using this approach.</p><p>Thank you for reading this article to the end. I hope you learned something new and you will be able to apply the knowledge in the practice.<br>Please make a CLAP if you like it) Have a good coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa498ec7268" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Delegate Pattern in MVP]]></title>
            <link>https://rasalexman.medium.com/delegate-pattern-in-mvp-4984e6b19e5?source=rss-3d9c0162b5f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4984e6b19e5</guid>
            <category><![CDATA[mvp]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mvp-development]]></category>
            <dc:creator><![CDATA[Alexandr Minkin]]></dc:creator>
            <pubDate>Tue, 13 Aug 2019 01:46:22 GMT</pubDate>
            <atom:updated>2019-08-13T10:49:34.291Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Delegate Pattern in MVP</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BCJUGm0N5u-eizY7KH0GFA.jpeg" /></figure><p>Hello developers. Today I want to explain delegation pattern, that can be a useful tool for separating user-interactions away from controller class (Fragment or Activity). Everybody uses some .setOnClickListener() or other listeners to handle user interactions in android applications. Controller classes may have a lot of code. So they are getting bigger and bigger with time, and it becomes difficult to manage them.</p><h3>CLASSIC MVP</h3><p>At first, I wanna discuss the classic <strong>MVP</strong> approach. This is a contract between <strong>VIEW</strong> and <strong>PRESENTER</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac045e24e6a442f8229b049cc55243f5/href">https://medium.com/media/ac045e24e6a442f8229b049cc55243f5/href</a></iframe><p>IBaseView.kt and IBasePresenter.kt know about each other as much as their contract support it. You can see the base view and presenter abstractions below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8617514032fb71bdeb93d8baad673a34/href">https://medium.com/media/8617514032fb71bdeb93d8baad673a34/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d44342bef3da2313b51900540ba696e/href">https://medium.com/media/4d44342bef3da2313b51900540ba696e/href</a></iframe><p>Their implementation contains the instances of each other and creates a relation through a contract that describes it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3bf40969f1ea4e031c8c68a7a73c1fc/href">https://medium.com/media/a3bf40969f1ea4e031c8c68a7a73c1fc/href</a></iframe><h3>DELEGATION PATTERN</h3><p>So what if we could separate our presenter from view?! Here comes the <strong>delegate pattern</strong> in our contract.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a8fd215d89804305cf3aa04065a4555/href">https://medium.com/media/1a8fd215d89804305cf3aa04065a4555/href</a></iframe><p>Where our IBaseDelegate.kt links the view and presenter. And since the presenter already knows everything necessary about the view it interacts, our delegate doesn’t need to keep the state of the view, as much as the view doesn’t need to keep presenter, because all interactions going throw delegate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0286ba460da1830b058f2abb817e85f1/href">https://medium.com/media/0286ba460da1830b058f2abb817e85f1/href</a></iframe><p>In this case, the delegate passes the view to the presenter and has interaction with it. <br>Next, we need to create BaseDelegate.kt . This is an abstract class that we must be implemented</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ff4d889e34e7ab9bdbe5a7da30c0156/href">https://medium.com/media/6ff4d889e34e7ab9bdbe5a7da30c0156/href</a></iframe><p>As you can see, I use “Kotlin Soft Keywords” <a href="https://kotlinlang.org/docs/reference/delegation.html">by</a> to implement a <strong>Delegation Pattern </strong>and attach the view to the presenter calling fun delegate() . Finally, we need to make a link to our view with BaseDelegate.kt and here we use another fragment class BaseDelegationFragment.kt</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85d99a5988a5737d5d651e624e917854/href">https://medium.com/media/85d99a5988a5737d5d651e624e917854/href</a></iframe><p>That is it. Now we can use our <strong>base delegate class</strong> to separate our UI interaction from the controller. val delegate: D is an instance of our IBaseDelegate.kt that already has the view and presenter. Here I use <a href="https://github.com/Kodein-Framework/Kodein-DI">Kodein</a> for dependency injection in child fragments. You can make your own base realization, maybe you want to have more than one delegate implementation, and it’s so easy to realize with this pattern. All you need to do is to add this delegate to the contract interface.</p><p>And the current fragment should look like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0d4b857d85550fcdab5ad6a4601ef1c/href">https://medium.com/media/f0d4b857d85550fcdab5ad6a4601ef1c/href</a></iframe><p>Here I use dependency injection by <a href="https://github.com/Kodein-Framework/Kodein-DI">Kodein</a>, but you can use your favorite DI like <a href="https://github.com/google/dagger">Dagger2</a>, <a href="https://github.com/InsertKoinIO/koin">Koin</a>, <a href="https://github.com/MichaelRocks/lightsaber">Lightsaber</a>, <a href="https://github.com/stephanenicolas/toothpick">Toothpick</a>, etc. I created all dependency graph in MainApplication.kt :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3948fdf4a3a26dee4792f22eca2002a5/href">https://medium.com/media/3948fdf4a3a26dee4792f22eca2002a5/href</a></iframe><p>Our AccountDelegate.kt should look like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d2c4a18b6327b9bebdfb243d3af7051/href">https://medium.com/media/6d2c4a18b6327b9bebdfb243d3af7051/href</a></iframe><p>1 — We need to override fun delegate() from IBaseDelegate.kt interface, where we pass all our UI interactions like event listeners, adapters and others… <br>2 — Take our view as Fragment into <a href="https://kotlinlang.org/docs/reference/scope-functions.html">with()</a> scope function from standard Kotlin library to get a reference to user interactions element such as buttons, tabs, menus, etc… by <a href="https://kotlinlang.org/docs/tutorials/android-plugin.html">synthetics</a> <br>3 — Set user interaction listeners into the scoped function<br>4 — Call presenter function</p><h3>Conclusion</h3><p>In this article, we examined the principle of separation of the user interface and the presenter using the DELEGATE pattern. Thus, we can easily separate user interaction, which can sometimes grow to a gigantic size in one fragment, from the logic of interaction with the presenter level, which allows us to write more flexible and convenient code. We also made our fragments easier. <br>Full code of this example you can see at my repo:</p><p><a href="https://github.com/Rasalexman/MVPDelegate">Rasalexman/MVPDelegate</a></p><p>Thank you for reading this story. Please make a CLAP and stay positive)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4984e6b19e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean MVVM Architecture (part 3)]]></title>
            <link>https://rasalexman.medium.com/clean-mvvm-architecture-part-3-386611969a3?source=rss-3d9c0162b5f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/386611969a3</guid>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Alexandr Minkin]]></dc:creator>
            <pubDate>Sun, 14 Jul 2019 00:48:16 GMT</pubDate>
            <atom:updated>2019-07-14T10:31:05.933Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone. This is a final part of stories about clean architecture and MVVM on Android. In the <a href="https://medium.com/@sphc/clean-mvvm-architecture-part-2-84df7bfa1831">previous part</a>, we talked about Domain Layer. In this article, I want to talk about <strong>Data Layer </strong>which<strong> </strong>is the main layer who can retrieve data streaming in the application. Data and Domain Layer has closely coupled with each other by abstractions. As you can remember, the level of domain logic contains the rules by which we can manipulate data (filter, sort and also provide them for the presentation layer), it can be reused many times by other parts of our application, and it can also consist of nested uses-cases. The data level provides us with the methods by which we can receive data, as well as save them to the local storage (if provided), and also provide the level of abstraction for our providers for which we receive data. It’s divided into two parts — Repository and Data Storages (such as Remote, Local or Memory Data Storages).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*-T8_b_tplj3gSR8SiJLTmg.png" /></figure><p>These objects are separated from the repository by the necessary level of abstraction since we cannot guarantee that they will not change in the future, but on the other hand, their implementation should not depend on what data we receive. For example, today we can use the <a href="https://developer.android.com/topic/libraries/architecture/room">Room from Google</a>, and tomorrow a new database will be released and we will want to use it. That is why this layer should be separated from the repository. Lets’s look at our implementation of GenresRepository.kt:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42ba43a3d787c148a21c26fa7bf4a0e8/href">https://medium.com/media/42ba43a3d787c148a21c26fa7bf4a0e8/href</a></iframe><p>as you can see we use only interfaces for Local and Remote Data Sources.</p><pre>interface IGenresRemoteDataSource {<br>    suspend fun getRemoteGenresList(): SResult&lt;List&lt;GenreModel&gt;&gt;<br>}</pre><pre>interface IGenresLocalDataSource {<br>    suspend fun getGenresList(): SResult&lt;List&lt;GenreEntity&gt;&gt;<br>    suspend fun insertGenres(data: List&lt;GenreEntity&gt;)<br>}</pre><p>Here we applied the <strong>DIP: The Dependency Inversion Principle</strong></p><blockquote>The modules of the upper levels should not depend on the modules of the lower levels. Both types of modules should depend on abstractions.</blockquote><blockquote>Abstractions should not depend on the details. Details must depend on abstractions.</blockquote><p>I recommend creating a separate repository for each data type, as well as local and remote data storage that we inject into our repository.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8b1c90bb1156a060a902f1fb0856374/href">https://medium.com/media/c8b1c90bb1156a060a902f1fb0856374/href</a></iframe><p>I use <a href="https://github.com/square/retrofit">Retrofit</a> to get our remote data from the server and I prefer to use <a href="https://github.com/square/moshi">Moshi converter</a> for our data models. Also, I use <a href="https://github.com/gildor/kotlin-coroutines-retrofit">gildor’s sealed classes</a> for better response handling. But in the newest version of retrofit (since 2.6.0), you can use suspend function without any third-party libraries. Thus, our remote data storage is responsible only for the logic of receiving a response from the server and its processing. In the future, if we want to use a different algorithm for processing server requests, all we need to do is implement the interface IGenresRemoteDataSource.kt and override the function suspend fun getRemoteGenresList(): SResult&lt;List&lt;GenreModel&gt;&gt;. Simple and flexible, right?! And now let’s get see the local data sourceGenresLocalDataSource.kt:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8248ccf5f3be540f532d0cd4da79e1de/href">https://medium.com/media/8248ccf5f3be540f532d0cd4da79e1de/href</a></iframe><p>So what if we need to store our data in local memory list, like array list, for better performance. We can extend IGenresLocalDataSource.kt and make something like this:</p><pre>interface IGenresLocalDataSource {<br>    suspend fun getGenresList(): SResult&lt;List&lt;GenreEntity&gt;&gt;<br>    suspend fun insertGenres(data: List&lt;GenreEntity&gt;)<br><br>    suspend fun putGenresInCache(genresList: List&lt;GenreEntity&gt;)<br>    suspend fun getGenresFromCache(): SResult.Success&lt;List&lt;GenreEntity&gt;&gt;<br>}</pre><p>Here, the separation of functions with different responsibilities may entail the worst consequences. Suppose again that tomorrow we changed the database and rewrote the class of local resources, in this case, we will also need to add the implementation of storing the data from the new database to the cache, and these are unnecessary maintenance costs or potential errors. The best solution here is to apply the <strong>ISP (Interface segregation principle)</strong>, which says:</p><blockquote>Clients should not depend on methods that they do not use.</blockquote><p>Now we can have two independent interfaces and accompany them separately, which gives us more flexibility and suitable for refactoring. I would also add that the correct use of <strong>ISP</strong> allows you to create optimal software models: to maintain a balance between minimum granularity and maximum code reuse.</p><pre>interface IGenresCacheDataSource {<br>    suspend fun putGenresInCache(genresList: List&lt;GenreEntity&gt;)<br>    suspend fun getGenresFromCache(): SResult.Success&lt;List&lt;GenreEntity&gt;&gt;<br>}</pre><pre>interface IGenresLocalDataSource {<br>    suspend fun getGenresList(): SResult&lt;List&lt;GenreEntity&gt;&gt;<br>    suspend fun insertGenres(data: List&lt;GenreEntity&gt;)<br>}</pre><p>We also share responsibility for their implementation if we using them separately in our repository.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be736003e4d468c9321e30fd1af3d8bd/href">https://medium.com/media/be736003e4d468c9321e30fd1af3d8bd/href</a></iframe><p>Now that how we have dealt with the <strong>DataLayer.</strong> I want to go back to the presentation layer again and show how easy and convenient we can create our ViewHolders.</p><h3><strong>Presentation Layer (ViewHolders)</strong></h3><p>To work with data mapping, I use <a href="https://github.com/Kotlin/anko">AnkoLayout</a> and Mike Penz library, <a href="https://github.com/mikepenz/FastAdapter">FastAdapter</a>. It is truly convenient and easy to use, especially since the latest versions are already fully translated into Kotlin. Since I have already created a base class for the adapter which will contain our maps</p><p>From <a href="https://medium.com/@sphc/clean-mvvm-architecture-part-2-84df7bfa1831">previous articles</a>, you noticed that I use the GenreUI.kt model for the presentation layer, let’s take a closer look at its contents.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f250ee82e750af77ba7b0a57f3c96398/href">https://medium.com/media/f250ee82e750af77ba7b0a57f3c96398/href</a></iframe><p>As you can see, I inherit from the base class BaseRecyclerUI.kt and override some of its methods. Look at how I create a view instance from <a href="https://github.com/Kotlin/anko">AnkoLayout</a> — GenreViewHolder.createView(AnkoContext.Companion.create(ctx, this)) . Here I use fun createView(ui: AnkoContext&lt;GenreUI&gt;) from ViewHolder and pass needed AnkoContext that was created from AnkoContext companion object function create(ctx: Context, owner: T, setContentView: Boolean = false) . This is the easiest way to create our <strong>view</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70a0948da14036b0fadbd5b221347b6d/href">https://medium.com/media/70a0948da14036b0fadbd5b221347b6d/href</a></iframe><p>We don’t need to set layoutRes cause we using <a href="https://github.com/Kotlin/anko">AnkoLayout</a> for our ViewHolders, and you can set type for specific items as you want. This is a simple FastAdapter item realization. The main interest is GenreViewHolder.kt</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea20d5365a2de7b3aba920cd3c695d2a/href">https://medium.com/media/ea20d5365a2de7b3aba920cd3c695d2a/href</a></iframe><p>I use the companion object to describe how our view layout will look like. And I don’t need to create another object) And after we described our interface and data assignment in the fun bindView(item: GenreUI, payloads: MutableList&lt;Any&gt;) , all we need to do is create instances of this class and pass them to the fast adapter object by calling itemAdapter.setNewList (see BaseRecyclerController.kt)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*UQ-8ZVSa2xJJ6sGRH6xBxQ.png" /><figcaption>AnkoLayout View</figcaption></figure><p>This is another example of more complex UI using MovieUI.kt model. You can see full code into my repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*D9bGxdRINvz64V-vy_L65g.png" /><figcaption>AnkoLayout UI</figcaption></figure><p>I love <strong>ANKO</strong> for its declarative style of interface description, but the project itself is developing very slowly and I am afraid that soon the company JetBrains will not support it anymore since Google released the new library <a href="https://developer.android.com/jetpack/compose">Compose</a>.</p><h3>Conclusion</h3><p>In all three articles, we have examined in sufficient detail the principles of building a clean architecture, as well as the usage of <strong>SOLID</strong> principles in the <strong>MVVM</strong> pattern. We also examined which objects can cross architectural boundaries (DTO), how to build a layout according to the declarative style (DSL) with the help of AnkoLayouts.<br> In the end, I want to say a few words about architecture as a whole:</p><blockquote>Architecture is the most important part of software development. This is the skeleton on which most of your program is built. A clean architecture and adherence to the principles of SOLID development, allows us to create flexible and easy-to-maintain software products.</blockquote><p>And of course:</p><blockquote>“If you think that good architecture is expensive, try bad architecture.”<br> — Brian Foote and Joseph Yoder</blockquote><blockquote>“Hurry unhurriedly.” — Robert Martin</blockquote><p>Thanks for reading these articles. I hope everyone discovered something new for yourself. Please make a <strong>CLAP</strong> and don’t forget to be amazing!)</p><p>Link to the repository:</p><p><a href="https://github.com/Rasalexman/MVVMClean">Rasalexman/MVVMClean</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=386611969a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean MVVM Architecture (part 2)]]></title>
            <link>https://rasalexman.medium.com/clean-mvvm-architecture-part-2-84df7bfa1831?source=rss-3d9c0162b5f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/84df7bfa1831</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alexandr Minkin]]></dc:creator>
            <pubDate>Tue, 09 Jul 2019 00:22:35 GMT</pubDate>
            <atom:updated>2021-04-13T20:58:29.233Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi again. This is the second part of articles about using clean architecture with MVVM and custom tech-stack. The first part you can find <a href="https://medium.com/@sphc/clean-mvvm-architecture-part-1-c90229ccb624">here</a></p><p>In this article, we going to talk about <strong>THE DATA FLOW</strong> that takes place in our clean architecture. In general, the choice of the mechanism of interaction with data in clean architecture should not depend on the choice of approach to the development of the application and user interactions. It can be either MVP or MVVM or MVI patterns. In fact, it does not matter. Only the presentation level changes. I choose MVVM cause it’s a little bit hyped today as like as MVI ;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*oEXqFhKACr0XtqC1CpNuYg.png" /></figure><p>Thin downward arrows in the figure marked input dependencies. A large thick arrow indicates an upstream data flow, which is carried out by transferring a Data Transfer Objects (next — DTO) across architectural boundaries, such as local and remote data storages, repositories, use-cases, and user interface. Now let’s look at one of the main components of our architecture, the <strong>data transfer object</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e45fee7a5b553bfcdf8a301ea2a7905a/href">https://medium.com/media/e45fee7a5b553bfcdf8a301ea2a7905a/href</a></iframe><p>This is a <a href="https://kotlinlang.org/docs/reference/sealed-classes.html">Kotlin sealed class</a>, that can store our results and transfer it throw architecture boundaries mapping the necessary object one to another. We will see how it can be later in this section. DTO represents the states of our data such as Loading , Empty , Error and Success results. Of course, there are can be more than four extended classes, and this is just an example. I simplify getting these types by wrapping it in high order and inline functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37093e259f714e05b5609a6101e0c7f2/href">https://medium.com/media/37093e259f714e05b5609a6101e0c7f2/href</a></iframe><h3>Domain level</h3><p>The domain level is such type of abstraction where we can manipulate our data flow. Let’s get see the simple example of how our use-case work.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c749ffc439cc6b9208c6b41c63a76458/href">https://medium.com/media/c749ffc439cc6b9208c6b41c63a76458/href</a></iframe><p>GetGenresUseCase.kt is a combined use-case that can do two actions: get already saved data and if there is no data, take it from the remote server. But on the fact, it did only single work, - <strong>get our data for presentation level. </strong>It doesn’t break the Single Responsibility Principle. In this class, I use <a href="https://kotlinlang.ru/docs/reference/coroutines.html">suspend function</a> called execute cause we <a href="https://youtrack.jetbrains.com/issue/KT-18707">cannot extend suspend function</a>, but in the next version of Kotlin it could be possible (i hope) and we will use class GetGenresUseCase : suspend ()-&gt;T or it’s <a href="https://kotlinlang.org/docs/reference/type-aliases.html">Typealias</a>. We already injected all of our dependencies through <strong>Kodein</strong> in <a href="https://medium.com/@sphc/clean-mvvm-architecture-part-1-c90229ccb624">the first part</a>, so I will not pay attention to this. So let’s look at the included use-cases.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bc535261ba6e3a38647fbbec7f3c29d/href">https://medium.com/media/1bc535261ba6e3a38647fbbec7f3c29d/href</a></iframe><p>From repository.getLocalGenreList(): SResult&lt;List&lt;GenreEntity&gt;&gt; takes the DTO with a list of our local entity models and maps it to the necessary DTO with the list of data for another layer - SResult&lt;List&lt;GenreUI&gt;&gt;. Here is a very important part, in that each layer of the architecture should work only with its inherent data and provide the necessary data format for the next layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86ab446032e25d4590a3242ff3df31f8/href">https://medium.com/media/86ab446032e25d4590a3242ff3df31f8/href</a></iframe><p>Another GetRemoteGenresUseCase.kt get data from remote service by repository implementation who produce only local entities, check it for success result (SResult.Success) and if it is not empty, save our data to local data storage. This is his single function! <br>Look at the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1EZwX8BTE-GoOD3ex36Vtw.png" /><figcaption>Data models flow diagram</figcaption></figure><p>As you can see, <strong>Data Layer</strong> works with two types of data, — Remote Model and Local Entity, but produce only Local Entity; <strong>Domain Layer</strong> work with Local Entities, it can get, save, sort, filter, etc and manipulate this type of data as it logic includes, then it should produce UI Model for <strong>Presentation Layer</strong>. We follow two principles of “SOLID” to map one type of data to another: OCP (The Open Closed Principle) and LSP (The Liskov Substitution Principle).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18e7085a7e796a305c9ce0aef6832d4e/href">https://medium.com/media/18e7085a7e796a305c9ce0aef6832d4e/href</a></iframe><p>We use this interface to hide converting realization:</p><pre>interface IConvertableTo&lt;T&gt; {<br>    fun convertTo(): T?<br>}</pre><p>Now, fun mapListTo() is not interested in the types of objects passed into List&lt;I&gt;. It simply calls their method convertTo(): O?. All it knows about types is that the objects it processes should belong to the interface IConvertableTo&lt;O&gt; or its implementations. And this is a current example of how we can do that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5eb3abde08d15402cf008ab6d560fa87/href">https://medium.com/media/5eb3abde08d15402cf008ab6d560fa87/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/190ed094d0178e6ef2cf9de8e91bb55f/href">https://medium.com/media/190ed094d0178e6ef2cf9de8e91bb55f/href</a></iframe><p>Now each data class itself decides how to convert one data to another. We cannot map our data if there is a null value in val id:Int? or val name: String? at the class GenreModel.kt, cause this is the main parameters that we use in <strong>UI Layer</strong> (GenreUI.kt) to show some information. We also use this.data.mapNotNull to exclude this situation. Of course, you can choose another mapping method or you can throw an error or filter empty entities in special use-cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90mfH7Bcm99CndubSwtKvg.png" /><figcaption>Mutate data flow diagram with boundaries</figcaption></figure><p>The picture illustrates how data flow and mutate from one boundary to another. This is the safest way to transfer data with DTO because each layer is only responsible for the consumption and production of its needed data types.</p><p>At this point, I want to finish the second part of the <strong><em>Clean Architecture</em></strong> articles.</p><h3>Conclusion</h3><p>We looked at how to make our <strong>domain layer</strong> more flexible, dividing the levels of responsibility and combining them, which gives us the opportunity to write flexible systems and repeatedly reuse the use-cases. We also saw how the <strong>Data Transfer Object (DTO)</strong> might look and how it is possible to mutate the data passing it across the architectural boundaries without breaking the principles of clean architecture. In the final topic, I will discuss the last architecture layer called <strong>Data Layer.</strong> It will be interesting. Also, I will show to you some UI tricks with AnkoLayout from JetBrain.</p><h4>There is a link to the repository:</h4><p><a href="https://github.com/Rasalexman/MVVMClean">Rasalexman/MVVMClean</a></p><p><strong>Thanks for reading this story.</strong> I hope you learned something new for yourself. It will be good if you give me some feedback and your recommendations for improving this article.<br>Please, click a <strong>CLAP</strong> and <strong>SHARE</strong> this post if you like it:)<br>Have a good day, coders!</p><p>The third part is here:</p><p><a href="https://rasalexman.medium.com/clean-mvvm-architecture-part-3-386611969a3">Clean MVVM Architecture (part 3)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84df7bfa1831" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean MVVM Architecture (part 1)]]></title>
            <link>https://rasalexman.medium.com/clean-mvvm-architecture-part-1-c90229ccb624?source=rss-3d9c0162b5f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c90229ccb624</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[mvvm]]></category>
            <dc:creator><![CDATA[Alexandr Minkin]]></dc:creator>
            <pubDate>Fri, 05 Jul 2019 00:20:54 GMT</pubDate>
            <atom:updated>2021-04-13T20:56:18.177Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hYZSFuhxODRa93HxM72FGw.png" /></figure><p>Hello developers. I know that there are a lot of articles about Clean Architecture and MVVM already exist on the web, but in this section, I want to share my own experience with the not standard tech-stack. This is <br>- Conductor Framework (<a href="https://github.com/bluelinelabs/Conductor">https://github.com/bluelinelabs/Conductor</a>)<br>- Anko Layouts (<a href="https://github.com/Kotlin/anko">https://github.com/Kotlin/anko</a>)<br>- KoDeIn Framework (<a href="https://github.com/Kodein-Framework/Kodein-DI">https://github.com/Kodein-Framework/Kodein-DI</a>)<br>- FastAdapter (<a href="https://github.com/mikepenz/FastAdapter">https://github.com/mikepenz/FastAdapter</a>)<br>and of course standard <a href="https://developer.android.com/topic/libraries/architecture/livedata">LiveData</a>, <a href="https://developer.android.com/topic/libraries/architecture/viewmodel">ViewModel</a> and <a href="https://developer.android.com/topic/libraries/architecture/room">Room</a> from Google, plus <a href="https://kotlinlang.org/docs/reference/coroutines-overview.html">Coroutines</a> from JetBrains. <br><strong>This will be the first part of the clean architecture and MVVM series.</strong></p><h3>Project Structure</h3><p>I’m going to start by explaining the project structure, the directories, and packages. So if you’re ready, let’s go right now!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*e6IQN4wSp5lNJMIXRXKK1Q.png" /></figure><p>The first two packages(<strong>“activity”</strong> &amp; <strong>“application”</strong>) have MainActivity.kt and MainApplication.kt classes that we’ll investigate later. The third one <strong>“common”</strong> package is for supported elements such as constants, utils, extensions and DTO (Data Transfer Objects). <strong>“datasource”</strong> package contains local and remote data sources with boundaries. <strong>“di”</strong> package store all modules that we use in dependency injection. <strong>“domain”</strong> is the place where our domain logic and repositories placed (models, repositories and use-cases). <strong>“view”</strong> package is our UI layer where we can place Controllers for layouts, UI models and view holders. And the final one is <strong>“viewmodel”</strong> package for our ViewModel classes.</p><h3>Dependency Injection</h3><p>I want to explain the “di” package at first. Let’s see what it includes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IJEinZHYM8FwZqjnx3QbeA.png" /></figure><p>I will consider the first module -DatabaseModule.kt as example. It includes all Dao object from the providers.database.dao package, which we will use later</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9d2eb5b940d5d553290730281735469/href">https://medium.com/media/d9d2eb5b940d5d553290730281735469/href</a></iframe><p>All we need to do to create Kodein module is to define it. The name of a module is required, and the binding of an object that can be singleton — means that only one instance would be in dependency graph or provider — means that the instance of an object would be created as soon as it will be needed in the dependency graph. Simple, right? :)</p><p>So the next step is to declare all our modules in Kodein for future injection and create necessary dependency sequences. MainApplication.kt is the rightest place to do this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57d9fe4014a69c8d1b3b8efdf152205c/href">https://medium.com/media/57d9fe4014a69c8d1b3b8efdf152205c/href</a></iframe><p>All we need to do is extend KodeinAware.kt and implement val kodein: Kodein as Kodein.lazy . It’s so easy to store all of your application dependencies in one place.</p><p>Ok. Let’s get look at the ViewModelFactory.kt as google docs say —</p><blockquote>Implementations of Factory the interface is responsible to instantiate ViewModels.</blockquote><p>Kodein also can do it for us. We just pass the context reference into ViewModelFactory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fee78ae95411b37064d145b3d76dfeb/href">https://medium.com/media/9fee78ae95411b37064d145b3d76dfeb/href</a></iframe><p>The main feature here is kodein.<em>direct</em>.Instance(<em>TT</em>(modelClass)) that create our view model objects. How to inject our view-model instances from factory class you will see later in this article.</p><h3><strong>Presentation Layer</strong></h3><p>Now I want to show you the UI layer (Presentation Layer) and how we can use our ViewModels. As I can say later I use <a href="https://github.com/bluelinelabs/Conductor">Conductor Framework</a>.</p><blockquote>It is a small, yet full-featured framework that allows building View-based Android applications.</blockquote><p>Let’s get see the base classes for all our view controllers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96b0743cca8bee62b2b38fec850c2ad9/href">https://medium.com/media/96b0743cca8bee62b2b38fec850c2ad9/href</a></iframe><p>As you can see I also use KodeinAware.kt to make my view controllers being injectable for dependencies. ViewBindController.kt implement LifecycleController.kt for ViewModel lifecycle. I have already created all supported classes to make controllers for UI with <strong>AnkoLayout</strong>. In package view.base.* you can find BaseRecyclerController.kt , BaseActionBarController.kt , BasePagerBackController.kt and many more.<br>So now let get to see how we create UI Controller and use our ViewModel classes. <br>We will create a simple application showing a list of movie genres from themoviedb.org:</p><p><a href="https://developers.themoviedb.org/3/genres">API Docs</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*IWENSzNsuutcPbhJmQPpWw.png" /><figcaption>movie genres from api</figcaption></figure><p>We will use Retrofit for HTTP calls and coroutines for callback result. I prefer to “Kotlin Coroutines for Retrofit” by <a href="https://github.com/gildor">gildor</a></p><p><a href="https://github.com/gildor/kotlin-coroutines-retrofit">gildor/kotlin-coroutines-retrofit</a></p><p>For local data store, we are going to use <a href="https://developer.android.com/topic/libraries/architecture/room">Room database from Google</a>. But now it doesn’t matter. We will see how to use these libraries in the next part )</p><p>Let’s return to our user interface controller:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e6da7d5a938865e4e59a5407bd67518/href">https://medium.com/media/9e6da7d5a938865e4e59a5407bd67518/href</a></iframe><p>This will be our <strong>root controller</strong> from which our navigation will begin, of course in real projects, the logic of choosing the root element for navigation may differ. We assign it to our main application activity MainActivity.kt.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f9c66f182916dec7a1c10e56f585124/href">https://medium.com/media/2f9c66f182916dec7a1c10e56f585124/href</a></iframe><p>Let us return to our root controller GenresController.kt and pay attention to how we inject our ViewModel:<br>private val genresViewModel: GenresViewModel by <em>viewModel</em>() <br>We use keyword by for our Kodein <a href="https://kotlinlang.org/docs/reference/delegated-properties.html">delegation</a> magic :) and <a href="https://kotlinlang.org/docs/reference/inline-functions.html">inline</a> <a href="https://kotlinlang.org/docs/reference/extensions.html">extension function</a> called <em>viewModel</em>() that lazily provide our ViewModel instance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b12957b5690c2f44174e69b0706dc407/href">https://medium.com/media/b12957b5690c2f44174e69b0706dc407/href</a></iframe><p>As you can see in this inline function, we use another <a href="https://kotlinlang.org/docs/reference/generics.html#upper-bounds">cool feature of the Kotlin</a> language called where. Thus, we can specify at once several dependencies that our generic type &lt;T&gt; should satisfy. So this is the simplest way to use our VM into the UI layer. And of course, we also add all our VM to the dependency graph in a dedicated module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed753977ad327a6008de91c3ee22560e/href">https://medium.com/media/ed753977ad327a6008de91c3ee22560e/href</a></iframe><p>Good. Now let’s look at what is in our <strong>view model</strong>. This is a simple class extended from the base class in which you need to pay attention to several aspects of implementation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d2ef49d84051bfff615bef7eb92166c/href">https://medium.com/media/9d2ef49d84051bfff615bef7eb92166c/href</a></iframe><p>As we follow the principles of clean architecture (<strong>here: </strong><a href="https://en.wikipedia.org/wiki/Single_responsibility_principle"><strong>Single Responsibility</strong></a>), we inject the dependency of our use-case into the VM.</p><ol><li>Create an instance of <a href="https://developer.android.com/topic/libraries/architecture/livedata">LiveData</a> that observes our data from the repository by using use-case. Also, we using coroutines with live data(since version 2.2.0) on separated IO thread and emit needed states for UI.</li><li>We provide a link to our created model for a UI so it is easy to remove the observer from it when our user interface is destroyed and we have no way to get a memory leak.</li></ol><p>We observer our LiveData in the controller by calling</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c4ad6d689dea6f349384b6b2693c2e1/href">https://medium.com/media/2c4ad6d689dea6f349384b6b2693c2e1/href</a></iframe><p>and handling results in this function fun handlerObserverResult by passing Data Transfer Object(DTO) as the parameter, that store our data flow states and results.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/570712fec60ad98718035a23d73cbfe8/href">https://medium.com/media/570712fec60ad98718035a23d73cbfe8/href</a></iframe><p>At this point, I want to finish the first part of the articles. <a href="https://medium.com/@sphc/clean-mvvm-architecture-part-2-84df7bfa1831">In the next section</a>, we are going to explore clean architecture deeper. I will show you how to use the domain logic and repository layer with the data flow. We will consider which objects can cross architectural boundaries and how to build interaction between the layers of clean architecture.</p><h3><strong>Conclusion</strong></h3><p>In this part, we looked at the structure of the project, the modules of dependencies, how to use <strong>Kodein</strong> with the main application activity file, and in individual components of our UI-controllers. We also saw how easy it is to create a view model and inject it into our interface controller with some Kotlin language features. And we looked at how to provide live data for our user interface. <br><strong>Thank you for reading this article.</strong> I will be very grateful for the feedback and your recommendations for improving this article.</p><h4>LINK TO REPOSITORY WITH EXAMPLE:</h4><p><a href="https://github.com/Rasalexman/MVVMClean">Rasalexman/MVVMClean</a></p><h4>PS:</h4><p>If you like this article and clean architecture please make a clap :)</p><p>The second part is here:</p><p><a href="https://medium.com/@sphc/clean-mvvm-architecture-part-2-84df7bfa1831">Clean MVVM Architecture (part 2)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c90229ccb624" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forget about Fragments with FlairFramework (part 1)]]></title>
            <link>https://rasalexman.medium.com/forget-about-fragments-with-flairframework-part-1-6f97dc63f845?source=rss-3d9c0162b5f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f97dc63f845</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlindev]]></category>
            <dc:creator><![CDATA[Alexandr Minkin]]></dc:creator>
            <pubDate>Sun, 05 Aug 2018 13:33:35 GMT</pubDate>
            <atom:updated>2018-08-24T15:10:30.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*zC4u3qEc98RCZe0H2c5xEg.png" /></figure><p>Hello everybody. In this article i’m going to talk about Android development without Fragments and Activities. I was worked with Fragments for 2 years and I always felt pain when I used them. Then I learned about the existence of a framework that does not use fragments, it’s called <a href="https://github.com/bluelinelabs/Conductor">Conductor</a> that was writen on Java. As i really love to develop Android applications with Kotlin, i start to search something looks similar to Conductor, but i didn’t find any results. After this, i was started to develop my own realisation of framework that does’t use a Fragments and was writen on clean Kotlin language. I was so inspired of Bluelinelabs work and my own last two frameworks (<a href="https://github.com/Rasalexman/ViamFramework">ViamFramework</a> &amp; <a href="https://github.com/Rasalexman/KotlinMVC">KotlinMVC</a>). And now, after spended a lot of time for hard work to complete this task, i want to represent to the community such a perfect result called <a href="https://github.com/Rasalexman/Flair">FlairFramework</a>. It’s create on top of MVC pattern with powerful event system (Observer Pattern), dependency injection and property delegation, also it support multi-core instances (Facade Pattern), backstack store for navigation and animation changes between views.</p><p>The main components of this framework is:</p><ol><li>‘flair’ instance is a simple IFacade singleton instance as core functionality point</li><li>SimpleCommand instances is a command pattern realisation. You can manipulate proxy objects from it’s instance as like UseCases</li><li>MacroCommands can combine more than one SimpleCommand and execute it one by one</li><li>Proxy objects is a complex object that store data to manipulate with, it’s like repository for ur network calls or database, also it can be a Presenters for your Mediators.</li><li>Mediator is a simple view-hierarchy handler class, it’s store and manage lifecycle of your view components such as <a href="/service/components:  &#39;flair&#39;%20instance%20is%20a%20simple%20IFacade%20singleton%20instance%20as%20core%20functionality%20point%20SimpleCommand%20instances%20is%20a%20command%20pattern%20realisation.%20You%20can%20manipulate%20proxy%20objects%20from%20it&#39;s%20instance%20as%20like%20usecases%20MacroCommands%20can%20combine%20more%20than%20one%20SimpleCommand%20and%20execute%20it%20one%20by%20one%20Proxy%20objects%20is%20a%20complex%20object%20that%20store%20data%20to%20manipulate%20with,%20it&#39;s%20like%20repository%20for%20ur%20network%20calls%20or%20database%20Mediator%20is%20a%20simple%20view-hierarchy%20handler%20class,%20it&#39;s%20store%20and%20manage%20life%20cicle%20of%20your%20view%20components%20such%20as%20AnkoComponents%20or%20xml-layout%20files.%20Also%20it%20support%20view%20backstack%20storage.%20Also%20you%20has%20LinearAnimator.kt%20for%20create%20simple%20view%20animation%20changes%20such%20as%20HorizontalAnimation,%20or%20u%20can%20extends%20LinearAnimator%20and%20create%20ur%20own%20realisation.%20All%20components%20of%20a%20FlairFramework%20are%20linked%20together%20by%20a%20powerful%20messaging%20system.%20You%20can%20notify%20every%20part%20of%20your%20system%20by%20calling%20sendNotification(event,%20data)%20and%20subscribe%20on%20event%20by%20calling%20registerObserver(event)%20{%20INotification%20-&gt;%20}%20in%20IMediator%20or%20execute%20another%20SimpleCommand%20(see%20example%20above).%20Mediator%20can%20notify%20commands,%20commands%20can%20notify%20mediators%20and%20another%20commands,%20proxy%20can%20notify%20mediators%20and%20another%20commands.">AnkoComponents</a> or xml-layout files. Mediators combines together with IView interface implementation as a part of MVC pattern that support view backstack storage for navigation.</li><li>Also you has LinearAnimator.kt for create simple view animation changes such as horizontal animation, or u can implement IAnimator.kt and create your own animation changes.</li><li>All components of a FlairFramework are linked together by a powerful messaging system (thanks to Observer Pattern). You can notify every part of your system by calling sendNotification(event, data) and subscribe on event by calling registerObserver(event) { INotification -&gt; } in IMediator or execute another SimpleCommand (see example above). Mediator can notify commands, commands can notify mediators and another commands, proxy can notify mediators and another commands.</li></ol><p>The start point for initialize framework is declare ‘flair’ instance in onCreate method in MainApplication.kt file or by the reference. But u can initialize framework in any part of your project such as MainActivity(you must extendFlairActivity ) or any Context implementations. See how it simple:</p><pre>class FlairApplication : Application() {<br>    /// That&#39;s how u register your &quot;flair&quot; components<br>    private val flairFirstCore = <em>flair </em><strong>{<br>        </strong><em>registerCommand</em>&lt;StartupCommand&gt;(<em>STARTUP</em>)<br>        <em>registerCommand</em>&lt;UserAuthCommand&gt;(<em>AUTH</em>)<br>        <em>registerCommand</em>&lt;AccountCommand&gt;(<em>ACCOUNT_CHANGE</em>)<br>        <em>registerCommand</em>&lt;AccountCommand&gt;(<em>ACCOUNT_CLEAR</em>)<br>        <em>registerCommand</em>&lt;LogicMacroCommand&gt;(<em>LOGIC_START</em>)<br>    <strong>}<br><br>    </strong>override fun onCreate() {<br>        super.onCreate()<br>        /*<br>        // alternative way to register components<br>        flair {<br>            registerCommand&lt;StartupCommand&gt;(STARTUP)<br>            registerCommand&lt;UserAuthCommand&gt;(AUTH)<br>            registerCommand&lt;AccountCommand&gt;(ACCOUNT_CHANGE)<br>            registerCommand&lt;AccountCommand&gt;(ACCOUNT_CLEAR)<br>            registerCommand&lt;LogicMacroCommand&gt;(LOGIC_START)<br>        }*/<br>    }<br>}</pre><p>The second part or using ‘Flair’ is attach created core to single Activity class and root layout container (but u can no specify any root container and flair take it for you automatically as activity.window.decorView.findViewById(android.R.id.content)). Important thing: only one activity (that should be an instance of FlairActivity) can be stored in one core of FlairFramework.</p><p>There is an example:</p><pre>class MainActivity : FlairActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        val showingAnimation = LinearAnimator()<br>        flair().attach(this).showLastOrExistMediator&lt;MyMediator&gt;(showingAnimation)<br>        // or with Anko<br>        // val rootContainer = frameLayout() <br>        // flair().attach(this, rootContainer).retrieveMediator&lt;MyMediator&gt;().show()<br>    }<br>}</pre><p>And Simple MyMediator.kt example is light-weight component that has only useful lifecyrcle methods such as :<br>- onPrepareCreateView() // called when view is ready to be created<br>- onCreatedView(view: View) // called when view is created but not added to container<br>- onAddedView(view: View) // viewComponent is added to root container<br>- onRemovedView(view: View) // viewComponent is removed from root container<br>- onDestroyView() // called when view is cleared and destroyed</p><pre>class MyMediator : Mediator() {</pre><pre>    // called when medaitor is registered<br>    override fun onRegister() {<br>      // register notification for this IMediator instance<br>      registerObserver(eventName:String) { notification -&gt;<br>            // event handler<br>      }<br>      sendNotification(eventName)<br>    }<br>  // the way to create UI<br>  override fun createLayout(context: Context): View = UserAuthUI().createView(AnkoContext.create(context, this)) <br>  // or you can inflate you custom xml layout<br>  // override fun createLayout(context: Context): View = inflateView(R.layout.simple_layout) <br>  <br>  inner class UserAuthUI : AnkoComponent&lt;MyMediator&gt; {<br>    override fun createView(ui: AnkoContext&lt;MyMediator&gt;) = with(ui) {<br>        verticalLayout {<br>            lparams(matchParent, matchParent)<br>            textView(&quot;HELLO WORLD&quot;)<br>        }<br>    }<br>  }<br>}</pre><p>From every Mediator instance you can call <br>- showMediator&lt;T:IMediator&gt;(mediatorName:String?) — to show another IMediator implementation , and if it’s not registered before, don’t worry, it will be registered if it doesn’t exist in mediator store. <br>- <em>popTo</em>Back() — it will goes back to previous mediator if it has and clear current mediator from backstack<br>- popTo&lt;T:IMediator&gt;(mediatorName:String?) — pop current mediator from backstack to given generic mediator or by it’s name.<br>- hide() — remove current mediator from root container</p><p>Simple right?!</p><p>This is a first part of using this powerful framework, where I tried to show you how easily you can build an independent ui with FlairFramework and the mediators. In the second part i will explain to you how to use Proxy objects and combine it with Commands. See my <a href="https://github.com/Rasalexman/Flair">githab</a> page with more complex examples. Thanks for reading this article. See you soon!</p><p>links: <a href="https://github.com/Rasalexman/Flair">https://github.com/Rasalexman/Flair</a></p><p>P.s.: I really want to get a feedback from developers to help me improve this project. I spend many times to make it better. So if you have any question or find some bugs please let me know about this to create an issue on github or write an email.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f97dc63f845" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KDispatcher simple and light-weight event bus for Kotlin]]></title>
            <link>https://rasalexman.medium.com/kdispatcher-simple-and-light-weight-event-bus-for-kotlin-e0fa4aaea1c7?source=rss-3d9c0162b5f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0fa4aaea1c7</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[eventbus]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Alexandr Minkin]]></dc:creator>
            <pubDate>Fri, 20 Jul 2018 19:16:28 GMT</pubDate>
            <atom:updated>2018-07-20T19:23:19.881Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*YK5PLgDKciZ0J66Ilvb9wQ.png" /><figcaption>by JetBrains</figcaption></figure><p>Hi everyone. This is my first story and i want to tell you about the great and useful android library that i was writen about one year ago. It’s called KDispatcher.</p><p>Now you can sequence many aspect of your Kotlin development with each other. It’s write on clear Kotlin with some of inline function and extension functions of that powerful language. First of all i want to say thanks to JetBrains (http://jetbrains.ru) and all <a href="http://kotlinlang.org/">http://kotlinlang.org/</a> team.</p><p>The main goals of it’s event dispatcher is:<br>1) Platform independent (you can use it in android app or backend or k/n apps)<br>2) It’s use an extensions function so it’s simple to integrate in your existing projects<br>3) KDispatcher has priority to sort your event handling function for execute one by one with given aspects<br>4) You can transfer any kind of data in you events notifications and you can listen another type of event in a single handler (see example project)<br>5) And for the final KDispatcher is thread-safe cause it use a kotlin singleton object to manipulate your events notifications</p><p>So i will start with some small example of how you can use it this library in you project. First of all you need to declare library implementation<br>Gradle:</p><pre>implementation &#39;com.rasalexman.kdispatcher:kdispatcher:x.y.z&#39;</pre><p>Maven:</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;com.rasalexman.kdispatcher&lt;/groupId&gt;<br>  &lt;artifactId&gt;kdispatcher&lt;/artifactId&gt;<br>  &lt;version&gt;x.y.z&lt;/version&gt;<br>  &lt;type&gt;pom&lt;/type&gt;<br>&lt;/dependency&gt;</pre><p>Then you have two choises how to use it:<br>1) you can simple use Singleton Object:</p><pre>val EVENT_CALL_ONE = &quot;simple_event_name&quot;<br>val eventListener = ::eventHandler<br>val priority = 1<br>KDispatcher.subscribe(EVENT_CALL_ONE, eventListener, priority)</pre><p>where:</p><ul><li>EVENT_CALL_ONE — simple eventName :String</li><li>eventListener — function listener for event</li><li>priority — the priority to sort calling functions</li></ul><pre>/**<br>* notif:Notification&lt;T:Any&gt; - event holder object that store<br>* data:T? = null - can be any type of data<br>* eventName:String? = null - current event type<br>* cause u may have more then one EVENT_TYPE for current event listener<br>*/<br>fun eventHandler(notif:Notification&lt;Any&gt;){<br>  when(notif.eventName){<br>      EVENT_CALL_ONE -&gt; println(&quot;FIRST EVENT with data ${notif.data}&quot;)<br>  }<br>}</pre><p>2) You can implement an IKDispatcher interface and has a control to manipulate your event inside you calling and subscribing objects like this</p><pre>class MyAnyClassCaller : IKDispatcher {<br>    // some work function<br>    fun doSomeWorkAndNotifyOthers() {<br>        //.... do some work<br>        val anyData:Any = &quot;String for data&quot;<br>        call(&quot;event_name_for_handling&quot;, anyData)<br>    }<br>}</pre><pre>class MyAnyClassListener : IKDispatcher {<br>    init {<br>      val priority = 1<br>      subscribe(&quot;event_name_for_handling&quot;, priority, ::eventHandler)<br>      // or<br>      subscribe(&quot;event_name_for_handling&quot;, 2) { notif -&gt;<br>           // do anything you want with notif.data and notif.eventName<br>      }<br>      // or without priority (default 0)<br>      subscribe(&quot;event_name_for_handling&quot;) {<br>         // do anything you want with it.data and it.eventName<br>      }<br>    }</pre><pre>    fun eventHandler(notif:Notification&lt;Any&gt;) {<br>    // do anything you want with notif.data and notif.eventName<br>    }<br>}</pre><p>And don’t forget to unsubscribe you event handlers when you don’t need it anymore with just one call unsubscribe(eventName, eventHandler?)</p><p>If you like this library, please share and support it on github:<br><a href="https://github.com/Rasalexman/KDispatcher">https://github.com/Rasalexman/KDispatcher</a></p><p>Also i need a feedback for future improvement and more core complex realisations. Thanks for reading and have a good coding)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0fa4aaea1c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>