<?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 Emanuel Moecklin on Medium]]></title>
        <description><![CDATA[Stories by Emanuel Moecklin on Medium]]></description>
        <link>https://medium.com/@1gravityllc?source=rss-be8d858ab85c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*gw6aXYAmz7nEzH6x9pjXgA.jpeg</url>
            <title>Stories by Emanuel Moecklin on Medium</title>
            <link>https://medium.com/@1gravityllc?source=rss-be8d858ab85c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 08:23:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@1gravityllc/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[Trie Kotlin]]></title>
            <link>https://1gravityllc.medium.com/trie-kotlin-50d8ae041202?source=rss-be8d858ab85c------2</link>
            <guid isPermaLink="false">https://medium.com/p/50d8ae041202</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[trie]]></category>
            <dc:creator><![CDATA[Emanuel Moecklin]]></dc:creator>
            <pubDate>Wed, 14 Sep 2022 16:55:00 GMT</pubDate>
            <atom:updated>2022-09-17T15:37:23.895Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nxJCLaqAkA7xIT0W.png" /></figure><p>Implementing an optimized <a href="https://en.wikipedia.org/wiki/Trie">Trie</a> in Kotlin or a short story on why I love Kotlin. Before reading on, make sure you understand how Tries work (not explained here). E.g.: <a href="https://en.wikipedia.org/wiki/Trie">Wikipedia</a>, <a href="https://medium.com/@saurav.agg19/implement-trie-prefix-tree-692560ea448a">Article 1</a>, <a href="https://medium.com/techie-delight/trie-data-structure-overview-and-practice-problems-2db1bad4bf49">Article 2</a> ...</p><p>TL;DR go straight to the code: <a href="https://github.com/1gravity/kotlin-trie">https://github.com/1gravity/kotlin-trie</a>.</p><h3>Node</h3><p>A typical node looks like this (<a href="https://en.wikipedia.org/wiki/Trie#Operations">Wikipedia</a>):</p><pre><strong>structure</strong> Node<br>   Children <strong>Node[</strong><em>Alphabet-Size</em><strong>]</strong><br>   Is-Terminal <strong>Boolean</strong><br>   Value <strong>Data-Type</strong><br> <strong>end structure</strong></pre><p>Many implementations don’t have the Value parameter, they only allow to search for keys: fun search(key: String): Boolean. <br>My implementation stores aValue → the signature of the search function is: fun search(key: String): Value?:</p><pre>data class Node&lt;Value&gt;(<br>    val children: MutableMap&lt;Char, Node&lt;Value&gt;&gt; = <em>mutableMapOf</em>(),<br>    var value: Value? = null,<br>)</pre><p>Note that there’s no Is-Terminal property (needed for deletion) because Is-Terminal is the same as node.value != null.</p><h3>Insert</h3><p>The basic implementation according to the pseudo code on <a href="https://en.wikipedia.org/wiki/Trie#Insertion">Wikipedia</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da2642ff2aa0790bf09c9ef356f2368d/href">https://medium.com/media/da2642ff2aa0790bf09c9ef356f2368d/href</a></iframe><p>The code traverses the Trie following the insert key and inserts missing nodes if needed. The last node will be set to value.</p><p>To traverse data structures in Kotlin the <a href="https://kotlinlang.org/docs/collection-aggregate.html#fold-and-reduce">fold function</a> is great. We can use the root node as initial value and return the child node in the lambda function till we reach the leaf node that becomes fold’s return value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21c7676c5a44837a10754d521467961c/href">https://medium.com/media/21c7676c5a44837a10754d521467961c/href</a></iframe><p>Now all we need is adding missing nodes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecb22b957271768d2976b488136f2a99/href">https://medium.com/media/ecb22b957271768d2976b488136f2a99/href</a></iframe><p>If a node is missing (node.children[char] == null), we create a new one and insert it.</p><p>Thanks to <a href="https://kotlinlang.org/docs/collection-aggregate.html#fold-and-reduce">fold</a>, <a href="https://kotlinlang.org/docs/scope-functions.html">scope functions</a> and the <a href="https://kotlinlang.org/docs/null-safety.html#elvis-operator">Elvis operator</a> we got this from 10 lines of code down to 5.</p><h3>Search</h3><p>The basic implementation according to the pseudo code on <a href="https://en.wikipedia.org/wiki/Trie#Insertion">Wikipedia</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4ee2615d92fc9123163faee95e60cf6/href">https://medium.com/media/a4ee2615d92fc9123163faee95e60cf6/href</a></iframe><p>Search is very similar to insert. Instead of adding nodes when finding a leaf, it returns null (key not found) and instead of inserting the value into the leaf, search returns it’s value (return currentNode.value).</p><p>Analogous to insert, we use the <a href="https://kotlinlang.org/docs/collection-aggregate.html#fold-and-reduce">fold</a> function to traverse the Trie:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b795c43127ca662f587aaab74507d74/href">https://medium.com/media/5b795c43127ca662f587aaab74507d74/href</a></iframe><p>If a leaf is found, its value is returned. If no leaf is found null is returned. From 10 lines of code down to 3.</p><h3>Delete</h3><p>The basic implementation converted from <a href="https://www.baeldung.com/trie-java">The Trie Data Structure in Java</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c9de6054481fd6faa33a34ef999168b/href">https://medium.com/media/0c9de6054481fd6faa33a34ef999168b/href</a></iframe><p>The delete function is a recursive function calling itself with an increasing index used to address characters in key.</p><p>The first statement ( if (index == key.length) is a stop condition: if we reach the last character of the search key, we found the node to be deleted. The function returns:</p><ul><li>null if the node was a leaf (was because the value was just deleted)</li><li>the deleted node itself, if it still has children (not a leaf)</li></ul><p>The second statement (val child = node...) is a stop condition too. If the next character can’t be found in the Trie → return null.</p><p>The rest of the code is the recursive part to traverse the Trie and delete the current node if the deletion further “down” the Trie made it “obsolete” (node.children.isEmpty() &amp;&amp; node.value == null).</p><p>There’s a lot of redundant code in this implementation, e.g. it checks twice whether the node is obsolete (once in the first stop condition, then again after the delete function calls). Let’s see how this can be improved.</p><ol><li>The return value is not needed. All it does is signal whether a node should be removed from its parent (no value &amp; no children). The parent node can check that itself: child.children.isEmpty() &amp;&amp; child.value == null. That alone simplifies the stop condition considerably:<br>if (index == key.length) node.value = null.</li><li>The second stop condition becomes a simple null check (use a scope function): node.children[key[index]]?.run { ... }.</li><li>The check to remove the child from its parent and the actual removal becomes a one liner: <br>if (children...) node.children.remove(key[index]).</li></ol><p>Putting all together we have:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc4d39851c0e4d86e36bce4b48eb710e/href">https://medium.com/media/bc4d39851c0e4d86e36bce4b48eb710e/href</a></iframe><p>From 17 lines of code down to 11.</p><h4>Encore: Non-Recursive</h4><p>Not everyone likes recursive algorithm so here’s an iterative delete implementation. To make this happen, we added a parent property to each Node (the insert function needed to be changed as well):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9da5c96481d1197e6817f1cae2e72a9a/href">https://medium.com/media/9da5c96481d1197e6817f1cae2e72a9a/href</a></iframe><p>Note the use of <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/fold-right.html">foldRight</a> to traverse the Trie bottom up (from leaf to parent, from search key right to left). The rest should be self-explaining.</p><h4>Encore 2: Cleanup</h4><p>A good amount of the delete code is needed to clean out unused nodes. If you don’t care about unnecessary memory allocations, delete can be simplified considerably:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fe33517ccee762e68863171a1d565df/href">https://medium.com/media/7fe33517ccee762e68863171a1d565df/href</a></iframe><h3>Summary</h3><p>While not every optimization uses Kotlin specific features, traversing the Trie is simple(r) using the <a href="https://kotlinlang.org/docs/collection-aggregate.html#fold-and-reduce">fold function</a> while <a href="https://kotlinlang.org/docs/scope-functions.html">scope functions</a> replace verbose null condition checks and “side effects”.</p><p>As always, thanks for reading and for your feedback.</p><p>Happy coding!</p><p>PS: how does this show my love for Kotlin? Just check out the gazillion Trie implementations out there…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50d8ae041202" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KMM UI Architecture - Part 2]]></title>
            <link>https://1gravityllc.medium.com/kmm-ui-architecture-part-2-e52b84aeb94d?source=rss-be8d858ab85c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e52b84aeb94d</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[ui-framework]]></category>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Emanuel Moecklin]]></dc:creator>
            <pubDate>Wed, 15 Jun 2022 18:18:21 GMT</pubDate>
            <atom:updated>2022-06-16T15:41:12.174Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*HvKqTjPsKIe8kW1JrAWgPA.png" /></figure><h3>Introduction</h3><p>This is part 2 of a series of two articles:</p><ul><li><a href="https://medium.com/p/6362e14ee52a">Part 1</a>: a summary of common ui patterns and what we learn from them</li><li><a href="https://medium.com/p/e52b84aeb94d"><strong>Part 2</strong></a><strong>: creating a simple, adaptable, predictable and composable UI framework for Kotlin Multiplatform</strong></li></ul><p>The patterns/frameworks discussed in part 1 serve as inspiration to define a UI framework for Kotlin Multiplatform. The essential ideas we take from them are:</p><ul><li>data flowing between model and view is immutable</li><li>data flows unidirectional from the view to the model and back</li><li>data flows are reactive</li><li>every concern is mapped to a component or a function to have clear separation</li><li>functions are first-class citizens</li></ul><p>What’s still unclear is:</p><ol><li>how to decompose/compose the user interface and the business logic</li><li>how state should be stored, in a single centralized store vs. decentralized, business logic component specific state</li></ol><p>In <a href="https://dev.to/feresr/a-case-against-the-mvi-architecture-pattern-1add">https://dev.to/feresr/a-case-against-the-mvi-architecture-pattern-1add</a> good questions are raised concerning point 1 and there’s obviously a good amount of discussion going on around the question single-store vs. multiple stores vs. local state containers.</p><p>The approach I took here is to be as un-opinionated as possible and support different “styles”. The goal was to create a framework that supports both centralized and decentralized approaches for business logic and state containers.</p><h3>Architectural Goals</h3><p>The architectural goals that helped shape the solution were:</p><ul><li>Be <strong>platform-agnostic</strong>: it’s a KMM framework so this is obvious.</li><li>Be <strong>reactive</strong>: reactive UIs have become the standard in recent years for good reasons.</li><li>Be <strong>composable</strong>: ability to decompose the ui into small components and combine them into larger components again.</li><li>Be as <strong>un-opinionated</strong> as possible: support different technologies, programming styles, app complexities and team sizes.</li><li><strong>Minimalistic</strong> and <strong>lightweight</strong>: some existing frameworks are very comprehensive but also heavyweight and require to write lots of boilerplate code (e.g. <a href="https://arkivanov.github.io/Decompose/">Decompose</a>). Strict contracts between components (leading to boilerplate code) are crucial in larger teams but they can bog down the team’s productivity when speed is crucial (and in smaller teams). A more strict approach should be supported but not enforced.</li><li>Be <strong>predictable</strong>: the order of execution (synchronous and asynchronous) and the concurrency model must be clearly specified and lead to predictable and repeatable outcome.</li></ul><h3>Kotlin Bloc</h3><p>Kotlin Bloc is the name of the framework to meet these architectural goals. Bloc stands for Business Logic Component, a term <a href="https://www.youtube.com/watch?v=RS36gBEp8OI&amp;t=1795s">created by Google</a> and popular in the <a href="https://bloclibrary.dev/#/">Flutter world</a>. The full framework documentation can be found here: <a href="https://1gravity.github.io/Kotlin-Bloc">https://1gravity.github.io/Kotlin-Bloc</a>.</p><h4>Overview</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1FUK78kqNSuuoJBQ" /></figure><p>The framework has two main components:</p><ul><li>The <strong>Bloc</strong> (Business Logic Component) encapsulates your application’s business logic. It receives <strong>Action</strong>(s) from the view, processes those actions and outputs <strong>Proposals</strong> and optionally <strong>SideEffect</strong>(s).</li><li>The <strong>BlocState</strong> holds the component’s <strong>State</strong>. It’s separate from the actual Bloc to support different scenarios like:<br>- share state between business logic components<br>- persist state (database, network)<br>- use a global state container like Redux</li></ul><p>The <strong>View</strong> is obviously an important component too but technically not part of the framework (although there are numerous <a href="https://1gravity.github.io/Kotlin-Bloc/docs/extensions/overview">extensions</a> that support/simplify the implementation for different target platforms).</p><p>Not surprisingly the Flutter Bloc nomenclature is used for some of the other components / sub-components of this architecture as well:</p><ul><li>A <strong>Sink</strong> is a destination for arbitrary data and used to send data from one to another component. A Bloc has a sink for <strong>Actions</strong> while a BlocState has a sink for <strong>Proposals</strong>.</li><li>A <strong>Stream</strong> is a source of asynchronous data. Stream are always “hot” meaning data is emitted regardless whether a component is listening (or subscribed or collecting -&gt; different names for the same thing). A Bloc has two streams, one for <strong>State</strong> and one for <strong>SideEffects</strong> while a BlocState has one for <strong>State</strong>.</li></ul><h4>Bloc</h4><p>The inner workings of a Bloc are depicted in the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mRdT3Bvk5yGa8On0" /></figure><p>The main parts of a Bloc are <strong>reducers</strong>, <strong>thunks</strong> and <strong>intializers</strong>.</p><p><strong>1. Reducer</strong></p><blockquote><em>A reducer is a function that receives the current state and an action object, decides how to update the state if necessary, and returns the new state: </em><em>(state, action) =&gt; newState<br>(</em><a href="https://redux.js.org/tutorials/fundamentals/part-2-concepts-data-flow"><em>https://redux.js.org/tutorials/fundamentals/part-2-concepts-data-flow</em></a><em>)</em></blockquote><p>Above definition is the official Redux reducer definition and captures its essence, although reducers in the context of Kotlin Bloc are a bit more complex:</p><pre>suspend (State, Action, CoroutineScope) -&gt; Proposal</pre><p>Compared to a Redux reducer, this one is:</p><ol><li>suspending</li><li>takes a CoroutineScope as parameter (on top of the State and the Action)</li><li>returns a Proposal instead of State</li></ol><p>There are different types of reducers which we’ll discuss more in the last chapter “Different Styles”. Here’s a simple example:</p><pre>// single-action reducer<br>reduce&lt;Increment&gt; { state + 1 }<br>reduce&lt;Decrement&gt; { state - 1 }</pre><pre>// catch-all reducer<br>reduce {<br>    when (action) {<br>        Increment -&gt; state + 1<br>        Decrement -&gt; state - 1<br>    }<br>}</pre><p><strong>2. Thunk</strong></p><p>While reducers are executed asynchronously, their intended purpose is to update State in a timely fashion to make sure the user interface is responsive to user input and updates &quot;without&quot; perceptible delay. Longer running operations should be executed using a Thunk:</p><blockquote><em>The word “thunk” is a programming term that means “a piece of code that does some delayed work”. Rather than execute some logic now, we can write a function body or code that can be used to perform the work later.<br></em><a href="https://redux.js.org/usage/writing-logic-thunks"><em>https://redux.js.org/usage/writing-logic-thunks</em></a></blockquote><p>A Thunk in the context of Kotlin Bloc is exactly what above definition implies, although its implementation and especially its execution is completely different from a Redux thunk. While the latter is a function, dispatched as an action to a Redux store and processed by the redux-thunk middleware, &quot;our&quot; thunk is not dispatched as an action but triggered the same way a reducer is triggered, by reacting to an Action that was sent to the Bloc. There are more differences:</p><ol><li>it’s a suspending function</li><li>it takes a CoroutineScope as parameter (next to the GetState, Action and Dispatcher parameters)</li><li>dispatching of Actions follows strict rules (explained <a href="https://1gravity.github.io/Kotlin-Bloc/docs/architecture/bloc/thunk#execution">here</a>)</li></ol><p>Here’s a simple example:</p><pre>thunk&lt;Load&gt; {<br>    dispatch(Loading)<br>    val result = repository.load()<br>    dispatch(Loaded(result))<br>}</pre><pre>reduce&lt;Loading&gt; {<br>    state.copy(loading = true)<br>}</pre><pre>reduce&lt;Loaded&gt; {<br>    state.copy(loading = false, items = action.result)<br>}</pre><p><strong>3. Initializer</strong></p><p>Initializers are functions executed when the bloc is created. They are similar to thunks since they can execute asynchronous code and dispatch actions to be processed by other thunks and reducers. Unlike thunks, initializers are executed once and once only during the <a href="https://1gravity.github.io/Kotlin-Bloc/docs/architecture/bloc/lifecycle">Lifecycle</a> of a bloc.</p><pre>onCreate { <br>    if (state.isEmpty()) dispatch(Load) <br>}</pre><h4>BlocState</h4><p>BlocState is the actual keeper of State, a source of asynchronous state data (StateStream) and a Sink for Proposals to (potentially) alter its state. Its interface is simple:</p><pre>// StateStream<br>public val value: State<br>public suspend fun collect(collector: FlowCollector&lt;State&gt;)</pre><pre>// Sink<br>public fun send(proposal: Proposal)</pre><p>The default BlocState implementation takes an accept() function to accept/reject <strong>Proposals</strong> as updates to <strong>State</strong> (taken from <a href="https://sam.js.org/">SAM</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/0*8i9DGS0CgD3SFVau" /></figure><p>Due to the clear separation between Bloc and BlocState, we can easily exchange a specific BlocState with another one, e.g. from our <a href="https://1gravity.github.io/Kotlin-Bloc/docs/examples/todo">todo app example</a>:</p><pre>fun toDoBloc(context: BlocContext) = bloc&lt;List&lt;ToDo&gt;, ToDoAction&gt;(<br>    context = context,<br><strong>    </strong><a href="https://1gravity.github.io/Kotlin-Bloc/docs/examples/todo"><strong>blocState = PersistingToDoState() </strong></a><br>) {</pre><p>PersistingToDoState is, as the name implies, storing to do data persistently. Changing one line of code can change that behavior (transparently for the Bloc):</p><pre>fun toDoBloc(context: BlocContext) = bloc&lt;List&lt;ToDo&gt;, ToDoAction&gt;(<br>    context = context,<br>    <strong>blocState = blocState(emptyList())     </strong><br>) {</pre><h3>Different Styles</h3><p>As mentioned before, we want to support different programming styles to support different types of apps, different level of complexities, different team sizes and different preferences on how to do things.</p><h4>Bloc</h4><p>One feature to support those goals are <strong>catch-all</strong> vs. <strong>single-action</strong> reducers that make it possible to write more monolithic reducers or more isolated ones:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b87099294c0f641d9f2c5867d9169b2/href">https://medium.com/media/3b87099294c0f641d9f2c5867d9169b2/href</a></iframe><p>The same syntax can be used for thunks and side effects as well:</p><pre>thunk&lt;Load&gt; { ... }<br>thunk&lt;Save&gt; { ... }<br>thunk { <br>    when(action) {<br>        Load -&gt; ...<br>        Save -&gt; ...<br>    }<br>}</pre><pre>sideEffect&lt;Load&gt; { ... }<br>sideEffect { ... }</pre><p>The “<a href="https://orbit-mvi.org/">Orbit</a>” model takes this idea one step further. The <a href="https://orbit-mvi.org/">Orbit</a> framework has the concept of a ContainerHost used for classes that want to launch Orbit intents:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac49b2eb5c0743e154d20dbd0f15b49e/href">https://medium.com/media/ac49b2eb5c0743e154d20dbd0f15b49e/href</a></iframe><p>Since any class can be a ContainerHost any class can contain reducer code addressing the main concern raised in <a href="https://dev.to/feresr/a-case-against-the-mvi-architecture-pattern-1add">this article</a>.</p><p>Kotlin Bloc has the concept of <a href="https://1gravity.github.io/Kotlin-Bloc/docs/architecture/blocowner/bloc_owner">BlocOwners</a>, an interface that can be implemented by any class and allows us to use the Orbit/MVVM+ syntax:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5c0c53e02536aaab36ff9bbab06078e/href">https://medium.com/media/e5c0c53e02536aaab36ff9bbab06078e/href</a></iframe><p>So we can declare reducers and thunks “builder style” (centralized in one builder block) or “BlocOwner style” (decentralized). Obviously we can also just use regular Kotlin features to decompose/compose business logic code (like extracting reducer code into separate functions or using extension functions).</p><h4>BlocState</h4><p>Another important feature that supports the “be un-opinionated” goal is the separation between state container (BlocState) and the actual business logic (Bloc) and the fact that the interaction between the two follows a strict protocol. This allows us to pick between a <strong>single-store</strong> vs. <strong>multiple stores</strong> vs. <strong>local state</strong> strategy (or a combination of the three).</p><p>We can e.g. share state between Blocs:</p><pre>// define the shared state<br>private val commonState = blocState&lt;BookState&gt;(BookState.Empty)</pre><pre>// first Bloc to use the commonState<br>private val clearBloc = bloc&lt;BookState, BookAction.Clear&gt;(<br>  context, <br>  commonState<br>) {<br>  // business logic<br>}</pre><pre>// second Bloc to use the commonState<br>private val loadBloc = bloc&lt;BookState, BookAction&gt;(<br>  context, <br>  commonState<br>) {<br>  // business logic<br>}</pre><p>We can also use a global state container like Redux to share state across all business logic components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iRw1aJ8Vd2PPwb0x" /></figure><p>As a matter of fact Kotlin Bloc comes with a <a href="https://1gravity.github.io/Kotlin-Bloc/docs/extensions/redux/redux_motivation">Redux adapter</a> that converts a Redux store to a BlocState and supports <a href="https://redux.js.org/usage/deriving-data-selectors">memoized selector functions</a>.</p><h3>Summary</h3><p>Kotlin Bloc is a simple and composable UI framework for Kotlin Multiplatform that will adapt to your programming style and integrates well into existing applications. It hits the sweet spot between guiding towards a certain way of implementing business logic, state containers and how to connect to the user interface without being too rigid.</p><p>Thanks for reading and I appreciate your feedback in the comments section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e52b84aeb94d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KMM UI Architecture - Part 1]]></title>
            <link>https://1gravityllc.medium.com/kmm-ui-architecture-part-1-6362e14ee52a?source=rss-be8d858ab85c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6362e14ee52a</guid>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[ui-framework]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Emanuel Moecklin]]></dc:creator>
            <pubDate>Wed, 15 Jun 2022 17:56:59 GMT</pubDate>
            <atom:updated>2022-06-16T02:36:08.912Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HvKqTjPsKIe8kW1JrAWgPA.png" /></figure><h3>Overview</h3><p>This is part 1 of a series of two articles:</p><ul><li><a href="https://medium.com/p/6362e14ee52a"><strong>Part 1</strong></a><strong>: a summary of common ui patterns and what we learn from them</strong></li><li><a href="https://medium.com/p/e52b84aeb94d">Part 2</a>: creating a simple, adaptable, predictable and composable UI framework for Kotlin Multiplatform</li></ul><h3>Problem Statement</h3><p>The promise of KMM (Kotlin Multiplatform Mobile) is literally:</p><blockquote>Write the business logic for your iOS and Android apps just once, in pure Kotlin (<a href="https://kotlinlang.org/lp/mobile/">https://kotlinlang.org/lp/mobile</a>)</blockquote><p>Unlike other cross-platform frameworks like Flutter or React Native, KMM does not promise a single code base for the user interface. This raises questions like:</p><ul><li>What exactly is the user interface?</li><li>How can the user interface be decomposed and which of the decomposed pieces are platform agnostic?</li></ul><p>By answering these questions we will be able to:</p><ul><li>better separate the different user interface components in general and the platform independent and the platform specific code specifically</li><li>increase the amount of code shared across target platforms</li></ul><p>To look at the problem and potential solutions from different angles, the first part of this series will explain some common architectural patterns like MVC, MVP, MVVM, MVI, SAM, BLoC, React/Redux and try to extract their essential ideas.</p><h3>UI Concerns</h3><p>In its most basic form, an ui architecture has two main concerns (I call it <em>concern</em> following the <a href="https://en.wikipedia.org/wiki/Separation_of_concerns">separation of concern principle</a>, which is “a design principle for separating a <a href="https://en.wikipedia.org/wiki/Computer_program">computer program</a> into distinct sections”, also heeding <a href="https://stackoverflow.com/a/25012230/534471">this advice</a> to ignore the academic discussion around <a href="https://en.wikipedia.org/wiki/Single-responsibility_principle">SRP</a> and <a href="https://en.wikipedia.org/wiki/Separation_of_concerns">SoC</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*b3hax5zvwi5Srzc3" /></figure><ol><li><strong>Display</strong>: show some content to the user = render state (in most models that’s the “view”)</li><li><strong>State Management</strong>: retrieve, store, transform state / data -&gt; business logic</li></ol><p>Two triggers exist:</p><ol><li>The user interacts with the displayed content which can lead to state changes which can lead to changes in the displayed content</li><li>State updates can be triggered by elements outside the ui framework, e.g. asynchronous network calls or device events (location updates, network events, incoming messages etc.) which can lead to changes in the displayed content</li></ol><p>Theoretically the code that displays can read and update the state directly or the code that manages state can listen to ui events to update itself and also update/manipulate the display directly. We all know that such a tightly coupled design is a terrible idea (on Android this was common practice before Google introduced <a href="https://developer.android.com/topic/libraries/architecture/viewmodel">ViewModels</a>). In order to achieve some decoupling we need “something” in between:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/0*muiUBPV4zCilQ12J" /></figure><p>Every ui architecture defines this “something” in between that:</p><ul><li>observes ui changes to update state</li><li>takes state and prepares it to be rendered</li></ul><p>The observant reader will have noticed that I just defined (at least) four more concerns:</p><ol><li><strong>Collect:</strong> listen to user interface events (keyboard, touch, mouse), filter events (e.g. debounce), aggregate events (e.g. aggregate touch events to a swipe to dismiss event)</li><li><strong>Transform:</strong> translate the result from the collect step into state changes (in some frameworks that result is called <em>intent</em>)</li><li><strong>Select:</strong> observe state and select the changes relevant for the user interface</li><li><strong>Bind:</strong> prepare state to be displayed e.g. by filtering relevant data and/or mapping it to a user friendly format like converting UTC timestamps to local timezone etc.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jv5M-dymjpX5Nnty" /></figure><h4>Intermezzo: Clean Architecture</h4><p>Now that we have a generic (alas abstract) ui architecture, let’s put it into the larger context of a <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">Clean Architecture</a> (skip this chapter if you’re not interested in Clean Architecture):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*hk5i4pky8jeD4ZVz.jpg" /></figure><p>While it was created with web and not mobile applications in mind, it’s still a useful model not just because of the proposed decomposition but because of the dependency rule:</p><blockquote>This rule says that <em>source code dependencies</em> can only point <em>inwards</em>. Nothing in an inner circle can know anything at all about something in an outer circle.</blockquote><p>Applying the <a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle">dependency inversion principle</a> across all layers of the architecture:</p><ul><li>no component has knowledge of a component living in an outer circle</li><li>components in an outer circle work with abstractions (e.g. interfaces) of components in inner circles</li></ul><p>When proposing a KMM ui architecture, we will follow this principle.</p><p>In his <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">original article</a>, “Uncle Bob” puts all the concerns we defined above into the green ring:</p><blockquote>It is this layer, for example, that will wholly contain the MVC architecture of a GUI. The Presenters, Views, and Controllers all belong in here.</blockquote><p>I hate to break it to you but I disagree with that statement.<br>The model in <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a> is not just data, it’s:</p><blockquote>the central component of the pattern. […] dynamic data structure […] directly manages the data, logic and rules of the application.</blockquote><p>According to this it’s also part business logic and as such also lives in the red “Use Cases” circle.</p><p>The view in <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a> obviously also lives in the blue circle. Even if the presenter creates all the HTML/CSS/JavaScript, we still need a browser (which lives in the blue circle) to render and collect user input.</p><p><a href="http://www.plainionist.net/Implementing-Clean-Architecture-Controller-Presenter/">This article</a> explains the interactions of view, presenter, controller and model/use cases in great detail and maps it all out for us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/0*vWCrqHU4ByTAlKmo.png" /></figure><p>This is exactly what we defined above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/0*aW4AK7_m5p7cOgDJ" /></figure><p>So in the context of a <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">Clean Architecture</a> our ui architecture spans across parts of the outer three layers.</p><h3>Existing Patterns / Frameworks</h3><h4>MVC (Model-View-Controller)</h4><p>When researching MVC, you’ll find that it’s anything but clearly defined. There are two main patterns:</p><ul><li>the <a href="https://tinyurl.com/mvctrianglemodel">triangle pattern</a> (which is the <a href="https://folk.universitetetioslo.no/trygver/themes/mvc/mvc-index.html">original pattern from 1979</a>): views interact directly with the model and the controller which also interacts directly with the model</li><li>the <a href="https://tinyurl.com/mvcchainmodel">chain pattern</a>: the controller interacts with the view and the model but there’s no direct interaction between the view and the model</li></ul><p>The chain pattern is what matches our own ui architecture with the controller being the “something” in-between:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/0*5Q38yg1ul-iiCfW3" /></figure><p>The interactions between the three components and the dependencies (which component knows what about what other component) aren’t clearly defined either. There are pull patterns, push patterns or reactive patterns and different levels of decoupling (view knows controller or view doesn’t know anything about the controller, controller knows model, controller works with injected model etc.). Due to this lack of consensus there’s really not much more we can learn from the MVC pattern.</p><h4>MVP (Model-View-Presenter)</h4><p>In MVP the presenter is the glue between the view and the model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/0*Vf3XY7GDwLhxDBg8" /></figure><p>The presenter updates the model and observes or receives updates from the model. In most implementations the presenter has a reference to the view and interacts with the view directly (like <a href="https://www.baeldung.com/mvc-vs-mvp-pattern">here</a> or <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter">here</a>) and vice versa (the view interacts with the presenter directly to forward ui events). Both view and presenter should be coded against interfaces but they still reference each other. MVP compares favorably to MVC in terms of decoupling but the presenter has too much responsibility and too much knowledge about the other components.</p><h4>MVVM (Model-View-View Model)</h4><p>There are two main differences between MVVM and MVP:</p><ol><li>The view model in MVVM has no reference to the view while in most MVP implementations the presenter has a reference to the view. View models are usually injected into the view.</li><li>MVVM introduces data binding between the view and the view specific part of the model to allow the separation of the gui development (the view) from the development of the business logic.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h7QcLIN4qFuKtT14" /></figure><p>The novelty of the MVVM model is the declarative data (model) and command (event) binding that eliminates virtually all gui code (and replaces it by some markup language like XML or <a href="https://en.wikipedia.org/wiki/Extensible_Application_Markup_Language">XAML</a>). In the absence of such binding technology one would typically use an MVP pattern.</p><h4>MVI (Model-View-Intent)</h4><p>MVI is mostly an Android/KMM pattern. Its novelty is the unidirectional and cyclical data flow inspired by the <a href="https://cycle.js.org/">Cycle.js framework</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*knUoGDn2_ksuMyG5gkIYyQ.png" /><figcaption>Source: <a href="https://cycle.js.org/dialogue.html">https://cycle.js.org/dialogue.html</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*u4Niqk66vmuiwrtz.jpg" /><figcaption>Source: <a href="https://github.com/arkivanov/MVIKotlin">https://github.com/arkivanov/MVIKotlin</a></figcaption></figure><p>MVI doesn’t mention the “Something” component that usually sits between the model and the view. It’s agnostic to the pattern used to glue these two components together. All it defines is:</p><ul><li>state is immutable data derived from the model and rendered by the view</li><li>user actions are translated into intents that are used to update the model (although in some definitions the intent is a function not a “thing”)</li><li>the data flow is unidirectional</li></ul><p>You can find several implementations of the pattern, e.g. <a href="https://arkivanov.github.io/MVIKotlin/">MVIKotlin</a>, <a href="https://pedroql.github.io/mvflow/">MVFlow</a>, <a href="https://orbit-mvi.org/Core/architecture">Orbit</a> or <a href="https://github.com/genaku/Reduce">Reduce</a> (list not exhaustive) and a great article about MVI <a href="https://hannesdorfmann.com/android/mosby3-mvi-1/">here</a>.</p><h4>SAM (State-Action-Model)</h4><p><a href="https://sam.js.org/">SAM</a> is a pattern for web applications but its concepts are worth discussing in the context of mobile apps. The two main ideas/concepts are:</p><ol><li>The view is a function of the model meaning there’s some piece of code converting the model into a state representation to be rendered / displayed by the view.<br>The piece of code performing the conversion from a model to a state representation is a function called State (the naming is unfortunate since state is data in all other patterns). In MVP the State would be part of the presenter, in MVVM this would be the binder.</li><li>View events are translated into a proposal to be presented to the model potentially resulting in model updates. <br>Actions are the functions that perform the translations from events to proposals. Proposals are the Intents in MVI.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TP70YuebHRwinYBzi3TKOw.png" /></figure><p>You see in the diagram that State functions can also trigger Actions before they create the state presentation so the flow in pseudo code is:</p><pre>// accept/reject proposal and alter state<br>model.accept(proposal)     </pre><pre>     // optional: trigger another action (State function)<br>     .then(nextAction)</pre><pre>     // create the state representation (State function)<br>     .then(createStateRepresentation)</pre><pre>     // render the state representation (View)<br>     .then(renderView)</pre><pre>     // record and send events (View)<br>     .then(sendEvent)</pre><pre>     // create a proposal (Action function)<br>     .then(createProposal)</pre><pre>     // and here we come full circle<br>     .then(acceptProposal)</pre><p>Like MVI, SAM defines an unidirectional flow between model and view and Actions are the Intents in MVI. So how is this different from MVI?</p><p>MVI only defines immutability, unidirectional flow and Intents as the vehicle to express the user’s intention. The rest is open to interpretation and different implementations have different solutions to fill the gaps.</p><p>SAM on the other side is more specific / precise in defining the different parts of the pattern, especially when it comes to defining what’s a function, an object or a data structure. E.g. State is a function as are Actions while State Representation is data. This matters because ultimately we need to make concrete decisions on what the “something” between a view and the model really is. Most patterns we have discussed so far are rather vague. E.g. the <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel">Wikipedia article about MVVM</a> describes the view model as:</p><blockquote>The <em>view model</em> is an abstraction of the view exposing public properties and commands. […]. MVVM has a <em>binder</em>, which automates communication between the view and its bound properties in the view model.</blockquote><p>It’s unclear what the view model really is. It exposes public properties (is it an object or a function?) but also commands (does it implement the <a href="https://en.wikipedia.org/wiki/Command_pattern">command pattern</a>?) and what is the binder, a class/object or a function?</p><p>With SAM it’s clear what’s what.</p><h4>BLoC (Business Logic Components)</h4><p>Blocs are a Flutter concept and very specific in defining the the interaction between the view and the bloc (the “something”) but doesn’t define how blocs and the model interact:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q4DZOVOGzCoCO6Xo" /></figure><ul><li>State is emitted by the Bloc as a stream and consumed by the view. A <a href="https://api.dart.dev/stable/2.15.1/dart-async/Stream-class.html">Stream</a> in Dart is the equivalent of an Rx <a href="http://reactivex.io/RxJava/3.x/javadoc/io/reactivex/rxjava3/core/Observable.html">Observable</a>(can be observed to retrieve emitted items).</li><li>Events are sent by the view to the Bloc into a sink. A <a href="https://api.dart.dev/stable/2.15.1/dart-core/Sink-class.html">Sink</a> in Dart is the equivalent of an Rx <a href="http://reactivex.io/RxJava/3.x/javadoc/io/reactivex/rxjava3/core/Observer.html">Observer</a> (can receive items).</li></ul><p>What’s new with Bloc is that it propagates reactive patterns between the view and the bloc and introduces naming conventions (event -&gt; sink, stream -&gt; state) that make sense because they are self explaining.</p><p>On top of that Bloc touches a topic we haven’t discussed yet, the <strong>decomposition</strong> of the ui into components.</p><h4>React / Redux</h4><p><a href="https://reactjs.org/"><strong>React</strong></a> itself is a framework to create declarative, composable GUI/web components. These components render the user interface, have a lifecycle and can have local state. There’s no mention of controllers, models, view models and such. As a result many different frameworks try to fill the gaps (state management and view binding). We’ll only discuss the most popular state management framework and its official binding library: Redux and <a href="https://react-redux.js.org/">React Redux</a>.</p><p><a href="https://redux.js.org/"><strong>Redux</strong></a><strong> </strong>is fairly simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/0*CmK-HjS9w7oCIe2c" /></figure><ul><li>The centralized <strong>store</strong> manages application state. It holds the current state (including the view state) and modifies it using <strong>reducers</strong>, which is a function with the signature: (state: State, action: Action) -&gt; State)</li><li>The view subscribes to state changes and updates itself accordingly</li><li>The view dispatches actions which are input for reducers</li><li>State is immutable and flows are unidirectional</li></ul><p>Other state management libraries/patterns like <a href="https://facebook.github.io/flux/">Flux</a> or <a href="https://facebook.github.io/flux/">MobX</a> are quite similar but use multiple stores instead of a single one. They all share the uni-directional flow of immutable state served by the store(s). While Redux covers state management and React the view part, we still need the “something” that connects these two.</p><p><a href="https://react-redux.js.org/"><strong>React Redux</strong></a> is the official React UI binding layer <a href="https://react-redux.js.org/api/connect">connecting</a> store state to component properties (Store -&gt; View, <a href="https://react-redux.js.org/using-react-redux/connect-mapstate">mapStateToProps</a>) and exposes functions to trigger state changes (View -&gt; Store, <a href="https://react-redux.js.org/using-react-redux/connect-mapdispatch">mapDispatchToProps</a>). Using React with Redux and React Redux pretty much follows the MVVM pattern with React Redux being the binder that is particular to MVVM.</p><p>I want to mention one more mechanism that is import to the interaction between views and store(s)s interact and that’s the use of selectors. If you’d subscribe to the store directly you’d get notified whenever anything changes even if it’s not relevant for a ui component. With the use of libraries like <a href="https://github.com/reduxjs/reselect"><strong>Reselect</strong></a> the view can select sub-state and retrieves updates only if that particular sub-state changes (the selectors are <a href="https://en.wikipedia.org/wiki/Memoization">memoized functions</a> that remember the result of previous calls).</p><p>React / Redux bring some new ideas to the table (compared to the other patterns we discussed earlier):</p><ul><li>A centralized, global state store</li><li>The concept of reducers to update the global state</li><li>Declarative ui components</li><li>Reactive patterns all over the place</li><li>Memoized selectors</li></ul><h4>Summary and outlook</h4><p>There’s an evolution in the last 40+ years that has brought us from tightly coupled components in <strong>MVC</strong> (in it’s <a href="https://folk.universitetetioslo.no/trygver/themes/mvc/mvc-index.html">original definition from 1979</a>) to decoupling of view and model via presenter in <strong>MVP</strong> to (tooling supported) data binding in <strong>MVVM</strong>.</p><p><strong>MVI</strong> adds immutable data and unidirectional flow to the equation while <strong>SAM</strong> formalizes the flow and defines state mutations and view binding as functions and as first class citizens of the design pattern.</p><p><strong>Bloc</strong> adds reactive programming and some useful nomenclature (bloc, stream, sink) while <strong>React/Redux</strong> introduce declarative ui components, a global state store (or multiple with Flux/MobX) and memoized selectors (among other things).</p><p>We will put all this together in <a href="https://medium.com/p/e52b84aeb94d">part 2</a> of this series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6362e14ee52a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Android ViewModels are obsolete in KMM]]></title>
            <link>https://1gravityllc.medium.com/why-android-viewmodels-are-obsolete-in-kmm-ecbd0124fad1?source=rss-be8d858ab85c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecbd0124fad1</guid>
            <category><![CDATA[ui-framework]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Emanuel Moecklin]]></dc:creator>
            <pubDate>Wed, 15 Jun 2022 05:10:53 GMT</pubDate>
            <atom:updated>2022-07-02T01:58:09.434Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*HvKqTjPsKIe8kW1JrAWgPA.png" /></figure><h3>The Problem</h3><p>One of the challenges on Android is that UI state needs to be saved and restored when configuration changes like screen rotations happen. Android <a href="https://developer.android.com/reference/androidx/lifecycle/ViewModel">ViewModels</a> were introduced to make this process as painless as possible.</p><blockquote>The <a href="https://developer.android.com/reference/androidx/lifecycle/ViewModel"><em>ViewModel</em></a> class is designed to store and manage UI-related data in a lifecycle conscious way. The <a href="https://developer.android.com/reference/androidx/lifecycle/ViewModel"><em>ViewModel</em></a> class allows data to survive configuration changes such as screen rotations.(<a href="https://developer.android.com/topic/libraries/architecture/viewmodel">https://developer.android.com/topic/libraries/architecture/viewmodel</a>)</blockquote><p>While designing and implementing a <a href="https://1gravity.github.io/Kotlin-Bloc/">UI framework for Kotlin Multiplatform</a> I found that existing frameworks use one of two approaches to address the (Android specific) UI state retention problem:</p><ol><li>Use a ViewModel on Android that proxies from the UI to the component that implements the business logic (let’s call it bloc = business logic component). The sole reason for the ViewModel to exist is to be lifecycle aware and retain state across configuration changes.<br>Touchlab has made a virtue out of this in their <a href="https://github.com/touchlab/KaMPKit">KaMPKit</a> and created a shared ViewModel with platform specific implementations so all business logic can be put into the shared ViewModel.</li><li>Add the ability to preserve state / retain instances in the bloc = business logic component. <a href="https://arkivanov.github.io/Decompose/">Decompose</a> e.g. is using <a href="https://github.com/arkivanov/Essenty">Essenty’s</a> StateKeeper and InstanceKeeper. This makes the bloc independent of the Android ViewModel (at least on the surface) but now it needs to explicitly save and restore state. This is imo a less than ideal solution especially because it’s a solution to a problem that exists on a single platform only.</li></ol><h3>A “better” Solution</h3><p>There’s a third way.</p><p>Just to recap, we need a bloc / business logic component that is lifecycle aware and is retained across configuration changes. This is how my solution looks like in an Activity or a Fragment:</p><pre>val bloc by getOrCreate { bloc(it) } // `it` is an Essenty lifecycle</pre><p>We’re using an <a href="https://github.com/arkivanov/Essenty">Essenty</a> lifecycle which is the platform-independent version of <a href="https://developer.android.com/reference/androidx/lifecycle/Lifecycle">Android lifecycle</a>. It’s passed as argument to the bloc and can be used by the business logic to start and stop and cleanup resources upon destruction (onDestroy() called).</p><p>Let’s see what’s under the hood:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54f27749ea94fad266d33f39259c19f8/href">https://medium.com/media/54f27749ea94fad266d33f39259c19f8/href</a></iframe><p>getOrCreate is an extension function of ViewModelStoreOwner lazily creating a component using the builder function (lifecycle: Lifecycle) -&gt; Component. Activities and Fragments are both ViewModelStoreOwner so we can call this from either.</p><p>ComponentLazy is a bit harder to understand:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10769c25e4cf8246fa2e7f74f7d0df47/href">https://medium.com/media/10769c25e4cf8246fa2e7f74f7d0df47/href</a></iframe><p>(Note: with androidx.lifecycle 2.5, the create function’s signature has slightly changed to: <br>override fun &lt;T : ViewModel&gt; create(modelClass: Class&lt;T&gt;): T<br>-&gt; T isn’t nullable any more)</p><p>Using the ViewModelStoreOwner we create a <a href="https://developer.android.com/reference/androidx/lifecycle/ViewModelProvider">ViewModelProvider</a> which will create ViewModels and retain them in a store of the given ViewModelStoreOwner. The get function returns an existing ViewModel or creates a new one in the scope (fragment or activity), associated with this ViewModelProvider. The created ViewModel is associated with the given scope and will be retained as long as the scope is alive (e.g. if it is an activity, until it is finished or process is killed):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72443b451712f4e248def4347d03745c/href">https://medium.com/media/72443b451712f4e248def4347d03745c/href</a></iframe><ul><li>The created ViewModel is a BlocViewModel which holds an Essenty Lifecycle and an Essenty InstanceKeeper:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b915dbc33ae2ff205a77b5f01a62928d/href">https://medium.com/media/b915dbc33ae2ff205a77b5f01a62928d/href</a></iframe><ul><li>Now we use this InstanceKeeperto either retrieve or create the Component. The Component is wrapped into a class than implements InstanceKeeper.Instance because only those can be store in an InstanceKeeper:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b85b8d01e14e4265c5383556424c238/href">https://medium.com/media/6b85b8d01e14e4265c5383556424c238/href</a></iframe><p>In a gist:</p><ul><li>The Component is stored in an InstanceKeeper</li><li>The InstanceKeeper is stored in a BlocViewModel which is an Android ViewModel</li><li>The BlocViewModel holds a Lifecycle tied to its own lifecycle. This lifecycle is used by the Component to manage its internal resources (coroutines, flows, channels etc.)</li><li>The BlocViewModel is stored in the ViewModelStore as long as its owner is alive meaning it will be retained across configuration changes</li></ul><h3>Summary</h3><p>We can create a shared / platform-independent business logic component and make it lifecycle aware on Android with a single line of code:</p><pre>val bloc by getOrCreate { bloc(it) }</pre><p>The code that makes this possible can reside in a shared module (androidMain). <a href="https://1gravity.github.io/Kotlin-Bloc">Kotlin Bloc</a>, a recently released UI framework for Kotlin Multiplatform, implements this mechanism.</p><p>Thanks for reading and for your feedback.</p><h4>Addendum</h4><p>Note that while using a ViewModel under-the-hood makes sure to retain the bloc across configuration changes, it won’t survive a process death.</p><p>In order to survive a system-initiated process death, you’d still have to use a <a href="https://developer.android.com/reference/androidx/lifecycle/SavedStateHandle">SavedStateHandle</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*pq5R2Tw6zRJ9J-rP52E-Uw.png" /><figcaption><a href="https://developer.android.com/topic/libraries/architecture/saving-states">https://developer.android.com/topic/libraries/architecture/saving-states</a></figcaption></figure><p>Whether your UI needs that kind of “retention” depends on your app. Depending upon the action a user takes, they either expect that activity state to be cleared or the state to be preserved.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecbd0124fad1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CI/CD for Android using GitHub Actions and Gradle Play Publisher]]></title>
            <link>https://1gravityllc.medium.com/ci-cd-for-android-using-github-actions-and-gradle-play-publisher-448bd8e42774?source=rss-be8d858ab85c------2</link>
            <guid isPermaLink="false">https://medium.com/p/448bd8e42774</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[gradle-play-publisher]]></category>
            <dc:creator><![CDATA[Emanuel Moecklin]]></dc:creator>
            <pubDate>Fri, 04 Feb 2022 06:16:05 GMT</pubDate>
            <atom:updated>2022-02-11T18:34:07.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*kvlk61jHfkDt409H.jpg" /></figure><p>Last year I published an article about <a href="https://medium.com/nerd-for-tech/ci-cd-for-android-using-bitbucket-pipelines-and-gradle-play-publisher-f00d6047ecb5">CI/CD using BitBucket Pipelines and Gradle Play Publisher</a>. This article explains how to do the same using <a href="https://github.com/features/actions">GitHub Actions</a> with two main differences (apart from the fact it’s using GitHub instead of BitBucket):</p><ul><li>I’ll use gradle files written in Kotlin (not Groovy)</li><li>I’ll also explain how to enroll the app in <a href="https://play.google.com/console/about/keymanagement/">Play App Signing</a></li></ul><p>A complete code sample can be found as part of one of my demo apps: <a href="https://github.com/1gravity/Android-ColorPicker">https://github.com/1gravity/Android-ColorPicker</a>.</p><h3>Overview</h3><p>There are five steps to setup the pipeline:</p><ol><li>We need programmatic access to Google Play to publish and promote apps (plus manage the meta data) -&gt; we need an API key for the <strong>Google Play Developer API</strong>.</li><li>The app needs to be enrolled in <a href="https://play.google.com/console/about/keymanagement/">Play Signing</a></li><li>We need to configure the <strong>Gradle build</strong> to use a signing configuration that reads the signing information from environment variables.</li><li>We need to configure the <strong>Gradle Play Publisher</strong> plugin to interact with Google Play (upload, publish apps and manage meta data).</li><li>We need to configure a <strong>GitHub Action</strong> to tie everything together.</li></ol><h3>Step 1: Google Play Developer API</h3><p>The official documentation explains all steps in detail: <a href="https://developers.google.com/android-publisher/getting_started">https://developers.google.com/android-publisher/getting_started</a>. Here’s a summary:</p><ul><li>Go to your <a href="https://play.google.com/console/developers">Google Play Developer Console</a> as owner of the account and open the <a href="https://play.google.com/console/api-access"><em>API access</em></a> page:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*b1tYdKiU2BNG8IGZ.png" /></figure><ul><li>Accept the Terms of Service (if not done yet)</li><li>Create a new Google Cloud project if you haven’t created one already (otherwise link an existing one).</li><li>Under “<em>Service Accounts”</em> click on <em>“Create new service account”</em> and open the link that leads to the Google Cloud Platform:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*SwnbpaKxmF8-rOxU.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*zShk_YP1mi2_No-J.png" /></figure><ul><li>In Google Cloud Platform click on <em>“CREATE SERVICE ACCOUNT”</em>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*G45yFIpntqf-ugGH.png" /></figure><ul><li>Pick a meaningful name and description before hitting the <em>“CREATE”</em> button:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/0*VVpIlOarKxd4RU5-.png" /></figure><ul><li>The account needs the role <em>“Service Account User”</em>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/0*MjpmudPztSjG8eSb.png" /></figure><ul><li>You don’t need to grant user access to the new service account, Google Cloud adds the required users automatically with the correct permissions (a Google Play service and your own user) so just hit <em>“DONE”</em>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/0*PZ-3ftinkpjf-ZKs.png" /></figure><ul><li>Next you need to create an API key for the account.<br>Open the actions menu (the three dots) and select <em>“Manage keys”</em>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*qquiCwNC4WrJltGI.png" /></figure><ul><li>Under <em>“ADD Key”</em> select <em>“Create new key”</em>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/0*yWBDTR-rPaJKnVxx.png" /></figure><ul><li>Create a JSON key:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/0*Ha8HYEavcakR8mM_.png" /></figure><ul><li>After hitting the <em>“CREATE”</em> button, the key file will be downloaded to your computer. I recommend to rename the file to make its purpose more obvious:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/0*rUt7U27gwNupn4wi.png" /></figure><ul><li>Now you’re done in Google Cloud Platform and you can go back to the Google Play Console (to the API access screen). The newly created account should appear under <em>“Service accounts”</em> (hit the <em>“Refresh service account”</em> button). Click on <em>“Grant access”</em>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*BAMdOGw7SFUEhzoD.png" /></figure><ul><li>Click on <em>“Add app”</em> and select all apps you want to manage with this service account:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*2kOGjtqQvzW98vuV.png" /></figure><ul><li>The Account permissions are already set correctly so that the service can manage all release related activities (create releases including publication to production, management of meta data etc.).</li><li>Click on <em>“Invite user”</em> and you’re done.<br>We will use the Gradle Play Publisher plugin to validate the API key setup later on.</li></ul><h3>Step 2: Enable Play App Signing</h3><p>If you have published an app just recently it’s likely already enrolled in Play App Signing (in which case you can skip this chapter and go to step 3), otherwise you need to follow the steps explained here: <a href="https://developer.android.com/studio/publish/app-signing#enroll">https://developer.android.com/studio/publish/app-signing#enroll</a>.</p><p>I will explain the process for one of my apps already published on Google Play. First you open the “<em>App integrity</em>” page in the Google Play Console (under “<em>Setup</em>”):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kc-khg5jBe7B8ikprBceHw.png" /></figure><p>Select the option “<em>Use existing app signing key from Android Studio</em>”. Before continuing open Android Studio and export the key by going to the “<em>Build/Generate Signed Bundle/APK</em>” and pick the “<em>Android App Bundle</em>” option:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*8cH3EALDuIYrDQUaLpLIbw.png" /></figure><p>Click “<em>Next</em>” and make sure “<em>Export encrypted key for enrolling published apps in Google Play App Signing</em>” is checked:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*nR9Fh_pvaS-9qyE-rCzyLw.png" /></figure><p>On the next screen select “<em>release</em>” as build variant (so it’s signed with the release key) and click “<em>Finish</em>”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*6zou6pGg2NplxtimYZD7LQ.png" /></figure><p>Now go back to the Google Play Console and click on the “<em>Upload private key</em>” link and upload the key you exported in the previous step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*PTu0MjnWMGlWyzMbm1yUsg.png" /></figure><p>“<em>Accept</em>” the terms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*esypEPWFxgwgIBzFibgKwQ.png" /></figure><p>You should now see a page like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BnrxsOGT8NoOvrBWjFv8cg.png" /></figure><h3>Step 3: Gradle Build</h3><p>The Gradle build needs to be configured to include a <a href="https://developer.android.com/studio/publish/app-signing">signing configuration</a> that reads the secrets from environment variables (or the gradle.properties file in your <em>~/.gradle folder</em>). If you already have one then you can skip this chapter.</p><p>The assumption is that you have a published app in Google Play and that you have access to the keystore and a signing key (or upload key) including the passwords (otherwise you would not have been able to complete the previous step).</p><p>For a local build the location of the keystore, the keystore password, the key alias and the key password will be configured in your ~/.gradle/gradle.properties file.</p><p>If you don’t have a ~/.gradle/gradle.properties file, please create one and add these four parameters (the bold part needs to be configured to fit your setup):</p><pre>KEYSTORE_FILE=/<strong>path to the keystore file</strong>/<strong>playstore.keystore</strong><br>KEYSTORE_PASSWORD=<strong>keystore password</strong><br>KEY_ALIAS=<strong>key alias</strong><br>KEY_PASSWORD=<strong>key password</strong></pre><p>Note: don’t use ~ for your home directory but use absolute paths. ~ works in a shell context but not with Gradle and Gradle Play Publisher.</p><p>Create a signing config in your app’s gradle.build.kts file:</p><pre>create(&quot;release&quot;) <strong>{<br>    </strong>storeFile = file(<em>project</em>.property(&quot;KEYSTORE_FILE&quot;).<em>toString</em>())<br>    storePassword = <em>project</em>.property(&quot;KEYSTORE_PASSWORD&quot;).<em>toString</em>()<br>    keyAlias = <em>project</em>.property(&quot;KEY_ALIAS&quot;).<em>toString</em>()<br>    keyPassword = <em>project</em>.property(&quot;KEY_PASSWORD&quot;).<em>toString</em>()<br><strong>}</strong></pre><p>Add the signing config to the build type:</p><pre>buildTypes <strong>{<br></strong>    getByName(&quot;debug&quot;) {<br>        // more stuff here<br>        signingConfig = signingConfigs.getByName(<em>name</em>)<br>    }<br><br><strong>    </strong>getByName(&quot;release&quot;) <strong>{<br></strong>        // more stuff here<br>        signingConfig = signingConfigs.getByName(<em>name</em>)<br>    }<br>}</pre><p>If the signing configuration is correct then the following command should run and create one or more aab files in your <em>build/outputs/bundle</em> folder</p><pre>./gradlew bundle</pre><h3>Version Code</h3><p>The version code of an app needs to increase with newer versions (see <a href="https://developer.android.com/studio/publish/versioning">https://developer.android.com/studio/publish/versioning</a>). Because there’s no easy way to define an auto-incrementing version number, we’ll use a version code derived from a UTC time stamp (see Step 5). In the app&#39;s <em>gradle.build.kts replace:</em></p><pre>versionCode = 124</pre><p>with:</p><pre>versionCode = <em>project</em>.<em>properties</em>[&quot;BUILD_NUMBER&quot;]<br>    ?.toString()?.<em>toInt</em>()?.minus(1643952714)<br>    ?: 124</pre><p>This will read the version code as a property and subtract 1643952714 (1643952714 = Fri, Feb 4, 2022 5:31:54 AM GMT) in order to make sure the version code doesn’t reach the max value of 2100000000 anytime soon (in around 14 years from now, 2100000000 = Fri, Jul 18, 2036 1:20:00 PM GMT). If no parameter is passed in (local build), it will take the version code after the Elvis operator ?:.</p><h3>Step 4: Gradle Play Publisher</h3><p>We are now able to build the app and create a signed bundle (or apk) but we still need to configure <a href="https://github.com/Triple-T/gradle-play-publisher">Gradle Play Publisher</a> to publish the signed app to Google Play.</p><p>We could also use <a href="https://fastlane.tools/">Fastlane</a> for this but I don’t recommend to go down that path (been there, done that). Trust me on this one…</p><p>Setting up the Gradle Play Publisher plugin is easy (see also <a href="https://github.com/Triple-T/gradle-play-publisher">https://github.com/Triple-T/gradle-play-publisher</a>):</p><ul><li>Add the plugin to the app’s gradle.build.kts file:</li></ul><pre>plugins {<br>    id(&quot;com.android.application&quot;)<br><strong>    id(&quot;com.github.triplet.play&quot;) version &quot;3.7.0&quot;<br></strong>    // other plugins<br>}</pre><ul><li>Add a configuration block to the app’s gradle.build.kts (after the android block):</li></ul><pre><strong><em>play </em>{<br>    val apiKeyFile = <em>project</em>.property(&quot;googlePlayApiKey&quot;).<em>toString</em>()<br>    serviceAccountCredentials.set(file(apiKeyFile))<br>    track.set(&quot;internal&quot;)<br>}</strong></pre><p>You’ll notice the “<em>googlePlayApiKey”</em> parameter. It’s a reference to the api key file we got when setting up the key for the service account -&gt; <em>google-play-api-key.json</em>. The parameter needs to be defined in ~/.gradle/gradle.properties (analogous the signing config parameters):</p><pre>googlePlayApiKey=/some-path/google-play-api-key.json</pre><p>If everything was setup properly, the following command, when run from the root directory of your app, will download the app’s meta data:</p><pre>./gradlew bootstrapListing</pre><h3>Step 5: GitHub Action</h3><h4>Repository Secrets</h4><p>First we need to configure the secrets passed to the Gradle build as parameters:</p><ul><li><em>GOOGLE_PLAY_API_KEY</em></li><li><em>KEYSTORE_FILE</em></li><li><em>KEYSTORE_PASSWORD</em></li><li><em>KEY_ALIAS</em></li><li><em>KEY_PASSWORD</em></li></ul><p>It’s easy to define the three values for <em>KEYSTORE_PASSWORD, KEY_ALIAS</em> and <em>KEY_PASSWORD</em> since they are just text values. To do so, go to the <em>“Repository settings”</em> and select <em>“Secrets / Actions”</em>. Enter all three variables with the correct values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*vonJTssLK0Xtojxn786fng.png" /></figure><p>To store the <em>KEYSTORE_FILE and the GOOGLE_PLAY_API_KEY</em> as a repository secret variables, we base64 encode the files. The build pipeline will decode it and recreate the original files (see below).</p><p>Run the following commands to encode the two files:</p><pre>base64 google-play-api-key.json &gt; google-play-api-key.json.base64<br>base64 playstore.keystore &gt; playstore.keystore.base64</pre><p>Copy the base64 strings and create repository secrets in GitHub. You should have something like this now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*pQIKOHXuCB9VazBEjz67Tg.png" /></figure><h4>GitHub Action</h4><p>We have the secrets, now it’s time to create the GitHub Action. First create a directories .github/workflows and and file publish_google_play.yml:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*pm5qSrtZGFiSuXz7W2mVBQ.png" /></figure><p>You can find a complete example in one of my demo apps <a href="https://github.com/1gravity/Android-ColorPicker/blob/master/.github/workflows/publish_google_play.yml">here</a> and since you can read up on the basics about GitHub Actions <a href="https://docs.github.com/en/actions">here</a>, I won’t explain all the details but focus on the specifics of the publishing process.</p><p>The <strong>build number</strong>: we mentioned above that we want to create a timestamp based version code and that’s how we do it:</p><pre><em># Create a build number based on timestamp / UTC time<br></em>- name: set release date<br>  run: |<br>    echo &quot;BUILD_NUMBER=$(date +&quot;%s&quot;)&quot; &gt;&gt; ${GITHUB_ENV}</pre><p>This defines an environment variable BUILD_NUMBER and assigns the timestamp (UTC) as a value.</p><p>The <strong>keystore file</strong> needs to be extracted from the secrets and written to a file since our Gradle build takes a file path/name as a parameter. We will use this action for this: <a href="https://github.com/timheuer/base64-to-file">https://github.com/timheuer/base64-to-file</a>.</p><pre><em># Decode the keystore file containing the signing key<br></em>- name: Decode Keystore<br>  id: decode_keystore<br>  uses: timheuer/base64-to-file@v1.1<br>  with:<br>    fileDir: &#39;./secrets&#39;<br>    fileName: &#39;my.keystore&#39;<br>    encodedString: ${{ secrets.KEYSTORE_FILE }}</pre><p>The Google Play API key file is extracted in the same way:</p><pre><em># Decode the Google Play api key file<br></em>- name: Decode Google Play API key<br>  id: decode_api_key<br>  uses: timheuer/base64-to-file@v1.1<br>  with:<br>    fileDir: &#39;./secrets&#39;<br>    fileName: &#39;google-play-api-key.json&#39;<br>    encodedString: ${{ secrets.GOOGLE_PLAY_API_KEY }}</pre><p>Now all that’s left to do is call Gradle with the right parameters:</p><pre><em># Build bundle and publish to Google Play<br></em>- name: Build &amp; publish to Google Play<br>  run: ./gradlew<br>    -PBUILD_NUMBER=&quot;${{ env.BUILD_NUMBER }}&quot;<br>    -PgooglePlayApiKey=&quot;../${{ steps.decode_api_key.outputs.filePath }}&quot;<br>    -PKEYSTORE_FILE=&quot;../${{ steps.decode_keystore.outputs.filePath }}&quot;<br>    -PKEYSTORE_PASSWORD=${{ secrets.KEYSTORE_PASSWORD }}<br>    -PKEY_ALIAS=${{ secrets.KEY_ALIAS }}<br>    -PKEY_PASSWORD=${{ secrets.KEY_PASSWORD }}<br>    publishBundle --max-workers 1</pre><p>That’s it. Enjoy and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=448bd8e42774" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The better Maven Central]]></title>
            <link>https://1gravityllc.medium.com/the-better-maven-central-90d7e529d606?source=rss-be8d858ab85c------2</link>
            <guid isPermaLink="false">https://medium.com/p/90d7e529d606</guid>
            <category><![CDATA[maven-central]]></category>
            <category><![CDATA[jitpack]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[maven]]></category>
            <dc:creator><![CDATA[Emanuel Moecklin]]></dc:creator>
            <pubDate>Tue, 12 Oct 2021 21:57:07 GMT</pubDate>
            <atom:updated>2021-10-13T13:02:38.923Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*kzaP1bFKNniDi5bJ.png" /></figure><p>Maven Central is the most used repository for Java artifacts. Almost every Gradle file starts with:</p><pre>buildscript <strong>{<br>    </strong><em>repositories </em><strong>{<br>       </strong> mavenCentral()<br>        // maybe other repos here        </pre><p>Yet publishing with Sontatype, OSSHR and Nexus (<a href="https://proandroiddev.com/publishing-a-maven-artifact-1-3-glossary-bc0068a440e0">this article</a> explains the terms really well) is a very slow and painful process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*XQTKggXHC14lfuhb" /></figure><p>Source: <a href="https://jfrog.com/blog/bintray-as-pain-free-gateway-to-maven-central/">https://jfrog.com/blog/bintray-as-pain-free-gateway-to-maven-central/</a>.</p><p>You could argue that Jfrog is biased but I fully agree with all the statements above. Now that the Jfrog alternative <a href="https://jfrog.com/blog/into-the-sunset-bintray-jcenter-gocenter-and-chartcenter/">JCenter is gone</a>, there’s imo only one solution left for open source projects and that solution is amazing: <a href="https://jitpack.io/">jitpack.io</a>.</p><p>Amazing because there’s literally no effort to publish artifacts once the maven or maven-publish plugin have been configured (which needs to be done in any case) -&gt; see my other article <a href="https://medium.com/nerd-for-tech/oh-no-another-publishing-android-artifacts-to-maven-central-guide-9d7f300ebd74">here</a>.</p><p>If you have a GitHub account there’s almost nothing to do to get Jitpack.io. going. Just grant Jitpack.io access to your public repos and you’re done. And with done I mean literally done.</p><p>Jitpack.io is so simple that I didn’t even notice that my artifacts e.g. for this repo: <a href="https://github.com/1gravity/Android-RTEditor">https://github.com/1gravity/Android-RTEditor</a> were automatically published (while I worked on the Maven Central publication). Jitpack automatically built and published my library:</p><ul><li>because it has access to my repos</li><li>because I tagged my commits with a version number, e.g. v1.7.3</li><li>because the maven-publish task was configured</li><li>because jitpack.io is an awesome tool ;-)</li></ul><p>To use the published artifacts you need to add jitpack.io as a Maven repo but that’s the only tiny drawback compared to artifacts published in Maven Central:</p><pre>allprojects {<br>    repositories {<br>	...<br>	maven { url &#39;https://jitpack.io&#39; }<br>    }<br>}</pre><p>I don’t need to go through Sonatype’s painful signup process and I don’t need to set up a build pipeline in the open source repository of my choice.</p><p>I did this for Android projects (e.g. <a href="https://github.com/1gravity/Android-RTEditor">here</a> and <a href="https://github.com/1gravity/Android-ColorPicker">here</a>) and backend Java projects (e.g. <a href="https://github.com/1gravity/Ktor-OpenAPI-Generator">here</a>), it’s equally simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*hzqNyOjLi9DOfgWq.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90d7e529d606" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Oh No - Another Publishing Android Artifacts to Maven Central Guide?]]></title>
            <link>https://1gravityllc.medium.com/oh-no-another-publishing-android-artifacts-to-maven-central-guide-9d7f300ebd74?source=rss-be8d858ab85c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d7f300ebd74</guid>
            <category><![CDATA[maven-central]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Emanuel Moecklin]]></dc:creator>
            <pubDate>Fri, 08 Oct 2021 19:53:44 GMT</pubDate>
            <atom:updated>2021-10-13T12:53:00.519Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kpy6bKisxkpSK1U99GvkaA.png" /></figure><p>Yes this is another guide on how to publish Android artifacts to Maven Central. Unlike other guides, it does cover extra “things” though:</p><ul><li>Gradle build files using <strong>Kotlin DSL</strong>.</li><li>Publish <strong>AAR file</strong> artifacts.</li><li>The publication includes a <strong>Source Jar</strong> file (hello withSourcesJar).</li><li>The publication includes a <strong>Javadoc Jar</strong> file (hello withJavadocJar).</li><li>The publication works with a <strong>CI/CD </strong>pipeline.</li><li>Did I mention this is <strong>Android only</strong>?</li></ul><p>For those who don’t like reading, here are two of my repos using the explained publish mechanism:</p><ul><li><a href="https://github.com/1gravity/Android-RTEditor">https://github.com/1gravity/Android-RTEditor</a></li><li><a href="https://github.com/1gravity/Android-ColorPicker">https://github.com/1gravity/Android-ColorPicker</a></li></ul><h3>Sonatype OSSRH</h3><p>Maven Central is really just a facade to multiple repositories. One such repository is <a href="https://central.sonatype.org/publish/publish-guide/">Sonatype OSSRH</a>. In order to publish your artifacts you need an account with them (or another repository provider). There’s a bunch of good articles on how to open an account and configure it properly. I’ll just reference those here and be done with it (it’s a cumbersome process so make sure you have time…):</p><ul><li><a href="https://central.sonatype.org/publish/publish-guide/">https://central.sonatype.org/publish/publish-guide</a></li><li><a href="https://mrcurious.medium.com/publishing-your-android-kotlin-library-to-maven-central-in-2021-df263a4f2cbc">https://mrcurious.medium.com/publishing-your-android-kotlin-library-to-maven-central-in-2021-df263a4f2cbc</a></li><li><a href="https://getstream.io/blog/publishing-libraries-to-mavencentral-2021/">https://getstream.io/blog/publishing-libraries-to-mavencentral-2021</a></li><li><a href="https://dev.to/madhead/no-bullshit-guide-on-publishing-your-gradle-projects-to-maven-central-3ok4">https://dev.to/madhead/no-bullshit-guide-on-publishing-your-gradle-projects-to-maven-central-3ok4</a></li><li><a href="https://www.waseefakhtar.com/android/publishing-your-first-android-library-to-mavencentral/">https://www.waseefakhtar.com/android/publishing-your-first-android-library-to-mavencentral</a></li></ul><h3>Plugins</h3><p>At this point the assumption is:</p><ul><li>You have an <strong>account</strong> with Sonatype OSSRH.</li><li>You created a repository with Sonatype OSSRH and have verified <strong>ownership of your domain</strong>.</li><li>You created a <strong>GPG key pair</strong> for signing artifacts, have published your public key and exported your private key.</li><li>You already have an app with build files in Kotlin DSL (compared to Groovy build files) -&gt; <strong>build.gradle.kts</strong>.</li></ul><p>Now step one is to add two plugins to your build file:</p><pre>plugins <strong>{<br>    </strong>id(&quot;com.android.library&quot;)<br><strong>    id(&quot;maven-publish&quot;)<br>    id(&quot;signing&quot;)<br>}</strong></pre><ul><li><a href="https://docs.gradle.org/current/userguide/publishing_maven.html"><strong>maven-publish</strong></a><strong>:</strong> provides the ability to publish build artifacts to an <a href="http://maven.apache.org/">Apache Maven</a> repository</li><li><a href="https://docs.gradle.org/current/userguide/publishing_signing.html"><strong>signing</strong></a><strong>:</strong> used to sign all artifacts and metadata files that make up a publication</li></ul><h3>Publish</h3><p>Step two is to create and configure the <em>publishing</em> extension by adding this to your gradle build file:</p><pre>afterEvaluate <strong>{<br>    </strong><em>publishing </em><strong>{<br>        </strong>publications {<br>            <strong>// here goes your configuration</strong><br>        }<br>    }<br>}</pre><p>The afterEvaluate makes sure the project has been evaluated and can be accessed in the config block.</p><p>The configuration consists of three steps:</p><ol><li>Configure the repositories</li><li>Configure the publication</li><li>Sign the artifacts</li></ol><pre>afterEvaluate <strong>{<br>    </strong><em>publishing </em><strong>{<br>        </strong>publications <strong>{<br>            <em>// 1. configure repositories<br>            // 2. configure publication<br>            // 3. sign the artifacts<br></em></strong>        }<br>    }<br>}</pre><h4>Repositories</h4><p>This part of the configuration defines the target repository. In our case it’s the Sonatype OSSRH, either the release or the snapshot repository.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcf09b9ca4c0c1d47d3f04a1d146ab5e/href">https://medium.com/media/bcf09b9ca4c0c1d47d3f04a1d146ab5e/href</a></iframe><p>The determination of the target repository is based on the version name. A version with a “-SNAPSHOT” suffix will be uploaded to the snapshot repo.</p><h4>Publication</h4><p>Configuring the publication is pretty straight forward.</p><p>First we define the artifacts to publish:</p><pre>from(<em>project</em>.<em>components</em>[&quot;release&quot;])<br>artifact(<em>tasks</em>.<em>named</em>&lt;Jar&gt;(&quot;withJavadocJar&quot;))<br>artifact(<em>tasks</em>.<em>named</em>&lt;Jar&gt;(&quot;withSourcesJar&quot;))</pre><p>project.components[&quot;release&quot;] are the artifacts produced by the Android project which in case of an Android library should be an <em>aar</em> file. The other two lines declare the Javadoc and the source jar file as artifacts to publish. Later in this article I’ll explain how these two artifacts are produced.</p><p>The rest of the configuration defines the Maven POM file, which is an XML representation of a Maven project (project meta information).</p><p>The most important properties to configure are the <em>groupId</em>, the <em>artifactId</em> and the <em>version</em> (e.g. for com.android.tools.build:gradle:7.0.2, the <em>groupId</em> is <em>com.android.tools.build</em>, the <em>artifactId</em> is <em>gradle</em> and the <em>version</em> is obviously <em>7.0.2</em>). All the other properties are optional parameters to define the software license, identify the company/developer, the source code etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db53a338148696cea73c644303e82b8c/href">https://medium.com/media/db53a338148696cea73c644303e82b8c/href</a></iframe><p>As you can see the properties are all read from project.properties which are the properties defined in one of the gradle.properties file (either the project or the library specific properties file). Here’s an example of such a properties file: <a href="https://github.com/1gravity/Android-RTEditor/blob/master/RTEditor/gradle.properties">https://github.com/1gravity/Android-RTEditor/blob/master/RTEditor/gradle.properties</a>.</p><p>Note that the username and the password for the repository aren’t defined in a project properties file but should be defined in your ~/.gradle/gradle.properties file (~ stands for your home directory) so that the credentials aren’t committed to source control. If you don’t have that file, you need to create it and add the credentials:</p><pre>ossUsername=&lt;your OSS user&gt;<br>ossPassword=&lt;your OSS password&gt;</pre><h4>Signing</h4><p>Signing the artifacts is simple:</p><pre><em>signing </em><strong>{<br>    </strong>sign(<em>publishing</em>.<em>publications</em>.getByName(publicationName))<br><strong>}</strong></pre><p>The signing plugin uses the key you created earlier (see “You created a <strong>GPG key pair</strong> for signing artifacts, have published your public key and exported your private key”). The plugin needs the <em>private key</em> file, the <em>keyId</em> and the <em>password</em> which you define in your ~/.gradle/gradle.properties file. Add this to the file:</p><pre>signing.secretKeyRingFile=/&lt;user&gt;/.gnupg/secring.gp<br>g<br>signing.keyId=&lt;last 8 characters of your key id&gt;<br>signing.password=&lt;the password&gt;</pre><p>Note that ~/.gnupg/secring.gpg won’t work since Android isn’t able to resolve ~ to your home directory.</p><p>That’s it. If you run ./gradlew publish from your project directory it will build and publish your library to Sonatype OSSRH. You still need to manually close and publish the library and while that can be automated too, you should be familiar with the manual process: <a href="https://central.sonatype.org/publish/release/">https://central.sonatype.org/publish/release/</a>.</p><h4>Signing with CI/CD</h4><p>Most build pipelines read secrets as strings but not from files (like the secretKeyRingFile we use above). While there are ways to feed files into a pipeline (for BitBucket Pipelines a description can be found <a href="https://medium.com/nerd-for-tech/ci-cd-for-android-using-bitbucket-pipelines-and-gradle-play-publisher-f00d6047ecb5">here</a>), it’s a rather cumbersome process. Better to avoid files at all.</p><p>In our case we can use in-memory PGP secret keys and passwords by calling useInMemoryPgpKeys before creating the signing task:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/518001a4744f88cee0855c59e035811f/href">https://medium.com/media/518001a4744f88cee0855c59e035811f/href</a></iframe><p>The three parameters are read from a property file if compiled locally, so put these values in your <em>~/.gradle/gradle.properties</em> file:</p><pre>signingKeyId=&lt;last 8 characters of your key id&gt;<br>signingKeyPassword=&lt;the password&gt;<br>signingKey=&lt;the key&gt;</pre><p>The key needs to be “armored” meaning converted to an encrypted representation of the file consisting entirely of text-mode only / ASCII characters. It also needs to be stripped of the typical wrapper <em>gpg</em> puts around the actual key (the “ — — -BEGIN PGP PRIVATE KEY BLOCK — — -” parts).</p><p>Use this one-liner to get the key value:</p><pre>gpg --export-secret-keys --armor &lt;KEY_ID&gt; |grep -v &#39;\-\-&#39; |grep -v &#39;=.&#39; |tr -d &#39;\n&#39;</pre><p>To run this in a build pipeline, you need to configure the secrets in the according secrets manager. For GitHub this looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*u9iaz8H8qOzxupYezj6u2g.png" /></figure><p>When defining the pipeline you need to pass in the secrets as parameters for gradle/gradlew.</p><p>For <a href="https://github.com/features/actions">GitHub Actions</a> the syntax is:</p><pre>./gradlew -PossUsername=${{ secrets.OSSRH_USERNAME }}</pre><p>For <a href="https://support.atlassian.com/bitbucket-cloud/docs/get-started-with-bitbucket-pipelines/">BitBucket Pipeline</a> the syntax is:</p><pre>./gradlew -PossUsername=$OSSRH_USERNAME</pre><h3>withSourcesJar</h3><p>In Java projects there’s an easy way to create Jar files for the source and the Javadoc:</p><pre><em>java </em><strong>{<br>    </strong>withSourcesJar()<br>    withJavadocJar()<br><strong>}</strong></pre><p>Unfortunately this doesn’t work in an Android project. Replicating withSourcesJar is rather simple though:</p><pre><em>tasks </em><strong>{<br>   </strong><em>register</em>&lt;Jar&gt;(&quot;withSourcesJar&quot;) <strong>{<br>        </strong><em>archiveClassifier</em>.set(&quot;sources&quot;)<br>        from(<em>android</em>.sourceSets.getByName(&quot;main&quot;).java.srcDirs)<br>    <strong>}<br>}</strong></pre><p>This registers a task named withSourcesJar. It creates a Jar file (hence the Jar type definition and uses the Android source directories (<em>android</em>.sourceSets.getByName(“main”).java.srcDirs) as input for the jar file.</p><h3>withJavadocJar</h3><p>Creating a jar file for the Javadoc is equally simple:</p><pre><em>tasks </em>{<br>   <em>archiveClassifier</em>.set(&quot;javadoc&quot;)<br>   dependsOn(named(&quot;withJavadoc&quot;))<br>   val destination = <em>named</em>&lt;Javadoc&gt;(&quot;withJavadoc&quot;)<br>                        .get()<br>                        .<em>destinationDir<br>   </em>from(destination)<br>}</pre><p>The only problem is that we need to create the Javadoc first before we can create the Jar file. As you can see above we’re referencing a task named withJavadoc that creates the actual documentation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4878ee91a14b146585a34daf280d0ac2/href">https://medium.com/media/4878ee91a14b146585a34daf280d0ac2/href</a></iframe><h3>Summary</h3><p>This is the code all put together:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9be88e537a8a9cada309d0d457ca6068/href">https://medium.com/media/9be88e537a8a9cada309d0d457ca6068/href</a></iframe><p>That code is used here:</p><p><a href="https://github.com/1gravity/Android-RTEditor/blob/master/RTEditor/build.gradle.kts">Android-RTEditor/build.gradle.kts at master · 1gravity/Android-RTEditor</a></p><p>and here:</p><p><a href="https://github.com/1gravity/Android-ColorPicker/blob/master/library/build.gradle.kts">Android-ColorPicker/build.gradle.kts at master · 1gravity/Android-ColorPicker</a></p><p>As usual if you have suggestions or questions, don’t hesitate to comment.</p><p>Happy coding!</p><h3>Addendum</h3><p>If you think publishing on Maven Central is cumbersome, you’re not alone. IMO there’s a better/much easier alternative: <a href="https://medium.com/nerd-for-tech/the-better-maven-central-90d7e529d606">The better Maven Central</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d7f300ebd74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An opinionated Kotlin backend service - Database / Migration / ORM]]></title>
            <link>https://1gravityllc.medium.com/an-opinionated-kotlin-backend-service-database-migration-orm-52527ce3228?source=rss-be8d858ab85c------2</link>
            <guid isPermaLink="false">https://medium.com/p/52527ce3228</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[exposed]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[ktorm]]></category>
            <category><![CDATA[ktor]]></category>
            <dc:creator><![CDATA[Emanuel Moecklin]]></dc:creator>
            <pubDate>Fri, 07 May 2021 18:10:40 GMT</pubDate>
            <atom:updated>2021-10-07T06:41:14.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qiu113ms6RGCYJcA.jpg" /></figure><p>This is the fourth part of my series on Kotlin based backend services.<br>If you missed the first three parts:</p><ul><li><a href="https://medium.com/p/87f814e3dffd">An opinionated Kotlin backend service - Framework</a></li><li><a href="https://medium.com/p/480ab5e6cdb2">An opinionated Kotlin backend service - Build &amp; Deployment</a></li><li><a href="https://medium.com/p/1e4b02aa6245">An opinionated Kotlin backend service - API Routing and Documentation</a></li></ul><h3>ORM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/0*2D-k7p9NCCqQQQQY.png" /></figure><p>There are roughly three ways to interact with a database:</p><ul><li>using SQL directly</li><li>using an SQL wrapping DSL</li><li>using ORM (object relational mapping)</li></ul><p>These are of course just rough categories and there’s all kinds of “in-between” solutions but I don’t want to elaborate on the the different approaches. My goal was <strong>not</strong> to create a framework for high volume, low latency transactions so I decided to go with an ORM.</p><p>From the Java world there are some obvious contenders:</p><ul><li><a href="https://hibernate.org/">Hibernate</a></li><li><a href="https://ibatis.apache.org/">iBATIS</a></li><li><a href="https://ebean.io/">EBean</a></li><li>many more…</li></ul><p>As usual I wanted a framework built for Kotlin with a clean and concise Kotlin DSL and none of the Java frameworks fit that bill. AFAIK there are really only two ORM frameworks built with Kotlin in mind:</p><ul><li><a href="https://github.com/JetBrains/Exposed">Exposed</a></li><li><a href="https://www.ktorm.org/">Ktorm</a></li></ul><p>Both offer a type-safe SQL wrapping DSL and also a DAO / entity API (the ORM). We’ll ignore the SQL wrapping part and focus on the ORM functionality. I my <a href="https://github.com/1gravity/Ktor-Template">Ktor template code</a> I implemented both frameworks and you can easily switch between the two in the <em>application.conf</em> file:</p><pre>; possible values: [KTORM, EXPOSED]<br>orm = &quot;KTORM&quot;</pre><p>Note that the API tests (article #5 of this series) run the tests twice, once using Ktorm, the second time using Exposed.</p><h4>DB Connection</h4><p>Connecting to the database is very simple with either of the frameworks:</p><pre>// Exposed<br>org.jetbrains.exposed.sql.Database.connect(<br>    url,<br>    driver,<br>    user,<br>    password,<br>)</pre><pre>// Ktorm<br>org.ktorm.database.Database.connect(<br>    url,<br>    driver,<br>    user,<br>    password,<br>    ConsoleLogger(LogLevel.<em>DEBUG</em>)<br>)</pre><p>Both can also use a javax.sql.DataSource, as is usually the case in enterprise applications to e.g. benefit from connection pooling. The syntax is identical for both frameworks: Database.connect(dataSource). A working code example including connection pooling (using <a href="https://github.com/brettwooldridge/HikariCP">HikariCP</a>) can be found in the <a href="https://github.com/1gravity/Ktor-Template/blob/31d654e6e98d3cb855b1844858f1f7dc6da74619/account-service/src/main/kotlin/com/onegravity/accountservice/persistence/database/DatabaseBaseImpl.kt">Ktor template</a>.</p><h4>Intermezzo: configuration in Ktor and dependency injection with Koin</h4><p>Before moving on to the next topic, I’d like to elaborate on how Ktor handles configuration (including the database configuration we just used).</p><p><em>application.conf</em> is usually the way to go with Ktor. There’s predefined properties that determine the deployment, security etc. as you can see <a href="https://ktor.io/docs/configurations.html#hocon-file">here</a>. You can also use environment variables like ${PORT} which can be injected into the runtime environment. You can also provide default values for those variables using this syntax:</p><pre>port = 5432<br>port = ${?DB_PORT}</pre><p>The configuration can be read in a module as this.environment.config (this referring to the Application class):</p><pre>environment.config.property(&quot;path.to.property&quot;)</pre><p>It would be easy to expose the configuration as a “static” variable or a top-level function to every component in the application. We do however want the ability to modify the configuration e.g. for testing purposes and since I’m already using <a href="https://insert-koin.io/">Koin</a> as a dependency injection framework, I decided to leverage DI. I created an interface Config exposing some convenience methods to access properties and created a simple Koin binding:</p><pre>single&lt;Config&gt; { ConfigImpl(environment.config) }</pre><p>To get access to the configuration, a component implements the KoinComponent interface and does:</p><pre>private val config by <em>inject</em>&lt;Config&gt;()</pre><p>or in case of a function (which can’t implement KoinComponent):</p><pre>val config = <em>getKoinInstance</em>&lt;Config&gt;()</pre><p>With getKoinInstance being:</p><pre>inline fun &lt;reified T&gt; getKoinInstance() =<br>    object : KoinComponent {<br>        val value: T by <em>inject</em>()<br>    }.value</pre><p>Note that my template actually takes the configuration from HoconApplicationConfig(ConfigFactory.load()) instead of environment.config. The former seems to be more the Java way to do it but honestly I don’t know if there’s a difference, both seem to work as expected.</p><h4>DB tables / entities</h4><p>The syntax for defining database tables and entities is very similar for both frameworks:</p><p><strong>Ktorm</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/720c27bd25d1a84510fb66649b1ba1a8/href">https://medium.com/media/720c27bd25d1a84510fb66649b1ba1a8/href</a></iframe><p><strong>Exposed</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09b88be8fbb31df947795e408a131a5e/href">https://medium.com/media/09b88be8fbb31df947795e408a131a5e/href</a></iframe><ul><li><strong>Bind table columns to entity properties</strong>: Ktorm does the binding in the table definition (.bindTo{ it.propertyName }) while Exposed does it in the entity (by Customers.propertyName). IMO it makes more sense to bind the entity to the table and I also prefer Exposed’s delegation syntax.</li><li><strong>Id definition:</strong> Both support primary keys with auto-increment or any other data type as primary key (without auto-increment of course). Exposed has a convenience class IntIdTable to eliminate the explicit need to define the primary auto-incremented key.</li><li><strong>Data types:</strong> Ktorm seems to support more data types<br><a href="https://www.ktorm.org/en/schema-definition.html#SqlType">https://www.ktorm.org/en/schema-definition.html#SqlType</a><br><a href="https://github.com/JetBrains/Exposed/wiki/DataTypes">https://github.com/JetBrains/Exposed/wiki/DataTypes</a><br>I had a bit of a struggle to get Postgres ENUMs to work properly (mostly with Exposed). Ktorm has a specific data type pgEnum in its Postres library (<em>org.ktorm:ktorm-support-postgresql</em>) that works out of the box. Exposed on the other hand requires to define a customEnumeration which doesn’t come out of the box and took me some time to find:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b34d70cdfacd8d281b2be2594048f8e4/href">https://medium.com/media/b34d70cdfacd8d281b2be2594048f8e4/href</a></iframe><ul><li><strong>References:</strong> Exposed has as more concise syntax compared to Ktorm:</li></ul><pre>reference(“account_id”, Accounts)</pre><p>compared to:</p><pre><em>int</em>(&quot;account_id&quot;).<em>references</em>(Accounts) { it.account }</pre><ul><li><strong>Entities:</strong> in Ktorm entities are interfaces which makes them hard to “re-use” e.g. as models for HTTP requests (you can’t serialize/deserialize interfaces with kotlinx.serialization e.g.). While data classes and regular classes are supported since version 2.5 (see <a href="https://www.ktorm.org/en/define-entities-as-any-kind-of-classes.html">here</a>), the limitations are too severe to make them a real alternative to interfaces (column binding not available, entities need to be created manually, entity manipulation API is not available). With Exposed the entities are regular classes (but not data classes) which is definitely more convenient.</li></ul><p>Overall Exposed is the clear winner when it comes to the basics of table and entity definition!</p><h4>Entity manipulation</h4><p>All the manipulation code is encapsulated in the two <em>AccountDao.kt</em> and <em>CustomerDao.kt</em> classes so you can easily compare the two frameworks</p><p><strong>Ktorm: </strong><a href="https://github.com/1gravity/Ktor-Template/blob/main/account-service/src/main/kotlin/com/onegravity/accountservice/persistence/model/ktorm/AccountDao.kt">Account.dao</a> / <a href="https://github.com/1gravity/Ktor-Template/blob/main/account-service/src/main/kotlin/com/onegravity/accountservice/persistence/model/ktorm/CustomerDao.kt">Customer.dao</a><br>Ktorm has the concept of an EntitySequence which is used to query entities. Inserting a new entity happens by adding an entity to the entity sequence, deleting and updating happens on the entity itself (after retrieving it from the entity sequence). Updates need to be explicitly written back using the flushChanges function.</p><p><strong>Exposed: </strong><a href="https://github.com/1gravity/Ktor-Template/blob/main/account-service/src/main/kotlin/com/onegravity/accountservice/persistence/model/exposed/AccountDao.kt">Account.dao</a> / <a href="https://github.com/1gravity/Ktor-Template/blob/main/account-service/src/main/kotlin/com/onegravity/accountservice/persistence/model/exposed/CustomerDao.kt">Customer.dao</a><br>Exposed’s manipulation API works off the entity itself: Entity.find() to query, Entity.new { } to insert new entities. Updates and deletes are performed on the entity directly and no need to “sync” the changes with the database, Exposed takes care of that. One inconvenience is that every database operation needs an active transaction. If you don’t wrap everything into a transaction { } call, it will fail with a “No transaction in context” error.</p><p>Overall the manipulation is straight forward in both frameworks and it’s mostly a matter of taste which one you prefer. I find the need to wrap each operation into transaction { } with Exposed not just an inconvenience (making the code more verbose) but also a potential source for bugs.</p><h3>Database Migration</h3><p>Schema versioning and migration is a problem that needs a good solution. I decided to look into <a href="https://www.liquibase.org/">Liquibase</a> and <a href="https://flywaydb.org/">Flyway</a>. As far as I could tell they both do the job. Liquibase’s advantage is to support XML, JSON and YML for the migration scripts on top of SQL which can be an advantage in a heterogeneous environment with multiple database technologies which would result in different SQL migration scripts (e.g. local development with H2 and testing/production using Postgres). Liquibase would support this use case with technology agnostic migration scripts in XML, JSON or YML. A good article comparing the two tools can be found here: <a href="https://medium.com/@ruxijitianu/database-version-control-liquibase-versus-flyway-9872d43ee5a4">Liquibase vs Flyway</a>.</p><p>I ultimately decided to use Flyway. There’s a free community edition which doesn’t allow dry runs and undo (down migration) as the two most severe limitations (IMO). After adding the Gradle dependency (<em>org.flywaydb:flyway-core</em>) all it needs it basically this piece of code:</p><pre>Flyway<br>    .configure()<br>    .dataSource(jdbcUrl, username, password)<br>    .load()<br>    .migrate()</pre><p>It will load the migration scripts from the resources folder and do the migration if needed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*wr0A5nNKEn0lSNSm8WpMTA.png" /></figure><p>That’s all. Make sure to stick to their versioning schema Vx__name.sql with two (sic!) underscores. Using a single underscore won’t work.</p><h3>Database Creation</h3><p>Flyway only creates and migrates schema but doesn’t create the database itself. Initially I created the database manually following some tutorials and articles like this one: <a href="https://medium.com/coding-blocks/creating-user-database-and-adding-access-on-postgresql-8bfcd2f4a91e">https://medium.com/coding-blocks/creating-user-database-and-adding-access-on-postgresql-8bfcd2f4a91e</a>. Since my template is running in a docker container, you also need to exec into the container to set everything up before Flyway can do its magic.</p><p>After having done that several times on different computers (time-consuming and error prone), I decided to automate the process and luckily found this answer: <a href="https://stackoverflow.com/a/61729115/534471">https://stackoverflow.com/a/61729115/534471</a>.</p><p>The solution is basically to create an <em>init-database.sh</em> script (see <a href="https://github.com/1gravity/Ktor-Template/blob/main/docker-databases/create-databases.sh">here</a>) and reference it in the <em>docker-compose.yml</em> file:</p><pre>volumes:<br>  - ./init-database.sh:/docker-entrypoint-initdb.d/init-database.sh</pre><p>No more manual creation of databases!</p><p>That’s it for part 4 of the series. If you enjoyed this, follow up with <a href="https://medium.com/p/87f814e3dffd">An opinionated Kotlin backend service - Testing</a>.</p><p>As usual feel free to provide feedback. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52527ce3228" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An opinionated Kotlin backend service - API Routing & Documentation]]></title>
            <link>https://1gravityllc.medium.com/an-opinionated-kotlin-backend-service-part-3-1e4b02aa6245?source=rss-be8d858ab85c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e4b02aa6245</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[openapi-generator]]></category>
            <category><![CDATA[ktor]]></category>
            <dc:creator><![CDATA[Emanuel Moecklin]]></dc:creator>
            <pubDate>Fri, 30 Apr 2021 16:16:23 GMT</pubDate>
            <atom:updated>2021-09-01T19:03:35.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YBST1qCD2cmdNuR_.jpg" /></figure><p>This is the third part of my series on Kotlin based backend services.<br>If you missed the first two parts:</p><ul><li><a href="https://medium.com/p/87f814e3dffd">An opinionated Kotlin backend service — Framework</a></li><li><a href="https://medium.com/p/480ab5e6cdb2">An opinionated Kotlin backend service — Build &amp; Deployment</a></li></ul><h3>API Routing and documentation</h3><h4>Ktor Routing</h4><p>Defining <a href="https://ktor.io/docs/routing-in-ktor.html">routes in Ktor</a> is simple and very concise due to the <a href="https://en.wikipedia.org/wiki/Domain-specific_language">DSL</a>. To define a route, call the routing function and add the routes you need:</p><pre>routing {<br>    // here go your routes<br>}</pre><p>Using different http methods:</p><pre>routing {     <br>    get(&quot;/customer/{id}&quot;) { /* handler */ }     <br>    post(&quot;/customer&quot;) { /* handler */ }     <br>    put(&quot;/customer/{id}&quot;) { /* handler */ } <br>}</pre><p>Grouped by path:</p><pre>routing {<br>    route(&quot;/customer&quot;) {<br>        get(&quot;/{id}&quot;) { /* handler */ }<br>        post(&quot;/&quot;) { /* handler */ }<br>    }<br>    route(&quot;/account&quot;) {<br>        get(&quot;/{id}&quot;) { /* handler */ }<br>    }<br>}</pre><p>Hierarchical:</p><pre>routing <strong>{<br>    </strong>route(&quot;/customer&quot;) <strong>{<br>        </strong>route(&quot;/order&quot;) <strong>{<br>            </strong>get(&quot;/{id}&quot;) <strong>{ </strong>/* handler */ <strong>}<br>            </strong>delete(&quot;/{id}&quot;) <strong>{ </strong>/* handler */ <strong>}<br>        }<br>    }<br>}</strong></pre><p>Modular (using extension functions):</p><pre>routing <strong>{<br>    </strong><em>customerByIdRoute</em>()<br>    <em>createCustomerRoute</em>()<br>    <em>orderByIdRoute</em>()<br><strong>}</strong></pre><pre>fun Route.customerByIdRoute() {<br>    get(&quot;/customer/{id}&quot;) <strong>{ </strong>/* handler */ <strong>}<br></strong>}<br><br>fun Route.createCustomerRoute() {<br>    post(&quot;/customer&quot;) <strong>{  </strong>/* handler */ <strong>}<br></strong>}<br><br>fun Route.orderByIdRoute() {<br>    get(&quot;/order/{id}&quot;) <strong>{ </strong>/* handler */ <strong>}<br></strong>}</pre><p>I don’t want to elaborate on the standard Ktor routing more in-depth because I’m actually not using it. If you’re interested to learn more about the regular Ktor routing read one of the numerous articles e.g. <a href="https://medium.com/playkids-tech-blog/building-simple-webservices-in-kotlin-using-ktor-59501f004070">here</a>, <a href="https://medium.com/dev-genius/create-simple-post-request-with-ktor-591deab01861">here</a> or <a href="https://medium.com/@billwixted/building-a-rest-api-with-ktor-4c322d31eb31">here</a>.</p><h4>OpenAPI Generation</h4><p>The reason I’m not using the normal Ktor routing function is explained in this article: <a href="https://medium.com/p/d57879ec5ab0">OpenAPI Generation with Ktor</a>.</p><p>The gist is that I wanted to have an OpenAPI documentation and I decided to write code and use a generator to create the documentation automatically (as opposed to writing documentation and generating the code automatically). The code I write looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03e59efccdd55f82233c8b0947a75d7c/href">https://medium.com/media/03e59efccdd55f82233c8b0947a75d7c/href</a></iframe><p>Definitions like the one above are used to:</p><ol><li>define the application routes</li><li>and generate the OpenAPI documentation:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*e1tiHsbRkxHX9310vxxjTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*t3UtuGrRLcarMBRRaaE5dw.png" /></figure><h4>Route Definition</h4><p>Let’s go through the definition step by step.</p><pre>tag(Tags.<em>Account</em>) <strong>{<br>    </strong>route(&quot;/api/v1/admin/accounts&quot;) <strong>{</strong></pre><ul><li>The <strong>tag function</strong> is used to group routes together (in this case into groups like <em>Misc</em>, <em>Customer</em> and <em>Account</em>).</li><li>The <strong>route function</strong> is used to define the routes matching a specific path.</li></ul><p>You can also create hierarchies of routes:</p><pre>route(&quot;/api/v1&quot;) <strong>{<br>    </strong>route(&quot;/misc&quot;) <strong>{ }<br>    </strong>route(&quot;/accounts&quot;) <strong>{ }<br>    </strong>route(&quot;/customers&quot;) <strong>{ }<br>}</strong></pre><p>The actual routes are defined within the route function:</p><pre><em>/**<br> * Create a new account.<br> */<br></em>post&lt;Unit, ResponseAccount, RequestAccount&gt;(<br>    <em>info</em>(<br>        summary = &quot;Create an account.&quot;,<br>        description = &quot;Create a new account&quot;<br>    ),<br>    <em>status</em>(HttpStatusCode.OK),<br>    exceptions = <em>listOf</em>(<em>badRequest</em>),<br>    exampleRequest = <em>accountExampleRequest</em>,<br>    exampleResponse = <em>accountExampleResponse<br></em>) <strong>{ </strong>_, account <strong>-&gt;<br>    </strong>val newAccount = controller.createAccount(account)<br>    respond(newAccount)<br><strong>}</strong></pre><p>The two or three generic types (two for a get: get&lt;AccountUUIDParam, ResponseAccount&gt; three for a post: post&lt;Unit, ResponseAccount, RequestAccount&gt;) define the types for</p><ol><li>path parameters (e.g. path/<strong><em>{accountUUID}</em></strong>)</li><li>response</li><li>request body (post, put)</li></ol><p>The definition of these types looks like this (path parameter):</p><pre>@Path(&quot;{accountUUID}&quot;)<br>data class AccountUUIDParam(<br>    @PathParam(&quot;UUID of the account.&quot;)<br>    val accountUUID: String<br>)</pre><p>or (response):</p><pre>@Response(&quot;Account Response.&quot;)<br>data class Account(<br>    val accountUUID: String,<br>    val createdAt: Instant,<br>    val modifiedAt: Instant,<br>    val status: AccountStatus<br>)</pre><p>These data classes are used to:</p><ul><li>Create the OpenAPI documentation:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*b5fuCnZ7Z7qpHQXnDBd8TQ.png" /></figure><ul><li>Define the result of serialization/deserialization of requests/responses (to and from Json / data classes)</li><li>Define object validation rules. Further down I will elaborate on object validation in more detail.</li></ul><h4>Method Parameters</h4><p>The method parameters for get, post, put, patch, delete and head functions are <em>almost</em> exclusively<em> </em>used to define the OpenAPI documentation (the exceptions parameters also tie into the object validation).</p><pre><em>info</em>(<br>    summary = &quot;Create an account.&quot;,<br>    description = &quot;Create a new account&quot;<br>),<br><em>status</em>(HttpStatusCode.OK),<br>exceptions = <em>listOf</em>(<em>badRequest</em>),<br>exampleRequest = <em>accountExampleRequest</em>,<br>exampleResponse = <em>accountExampleResponse</em></pre><ul><li>The purpose of the <strong>info</strong> and <strong>status</strong> parameters is obvious (describe the route and the response status code). They are both RouteOpenAPIModule vararg parameters of which there are two more: <br>1) resonseAnnotationStatusCode: the response HTTP status code is derived from the response definition, e.g: <br>@Response(&quot;Account Response.&quot;, <strong>202</strong>) -&gt; overrides the status(HttpStatusCode.OK) statement<br>2) tags<em>: </em>sets the tag for this route, if multiple tags are set, the route will appear in all the categories / groups.</li><li>The <strong>exceptions</strong> parameter defines possible error cases.</li></ul><p>E.g. the badRequest definition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29931e98308e4ff823d6721042b96121/href">https://medium.com/media/29931e98308e4ff823d6721042b96121/href</a></iframe><p>translates to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*9vctaLUVcvCkeq8u7FIlxg.png" /></figure><p>Note that the runtime error defined with contentFn depends on the exception message which is taken from the ConstraintViolation thrown as part of the validation process (see “Object Validation” chapter below).</p><ul><li>Last but not least the exampleRequest and exampleResponse parameters which should be self explaining.</li></ul><h3>Object validation</h3><p>I’ve written a dedicated article about object validation: <a href="https://medium.com/p/c7e02b5dabc">Object validation in Ktor/Kotlin</a>. In this article I researched several validation libraries like <a href="https://github.com/rcapraro/kalidation">Kalidation</a>, <a href="https://github.com/valiktor/valiktor">Valiktor</a> or <a href="https://github.com/konform-kt/konform">Konform</a>. While I declared Konform my favorite, I actually don’t use it because the <a href="https://github.com/1gravity/Ktor-OpenAPI-Generator">Ktor-OpenAPI-Generator</a> has a built-in validation mechanism. While I’m not a particular fan of annotation based validation (I like to use a single language for <em>everything</em> including configuration and build, that single language being Kotlin here), the advantage in this case is that it serves two purposes:</p><ol><li>Validation</li><li>Documentation</li></ol><p>E.g. the annotations here are used by the <a href="https://github.com/1gravity/Ktor-OpenAPI-Generator">Ktor-OpenAPI-Generator</a> to validate the input parameters and also to create the documentation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4a0ae355b1c024667da19ad1965ff2c/href">https://medium.com/media/d4a0ae355b1c024667da19ad1965ff2c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*rofHdTHd7yg4KXLvVcBvSw.png" /></figure><h4>Error Handling</h4><p>What happens if an input parameter or the request body fails validation?</p><p><a href="https://github.com/1gravity/Ktor-OpenAPI-Generator">Ktor-OpenAPI-Generator</a> throws a ConstraintViolation which is handled by the badRequest definition posted above:</p><pre>val <em>badRequest </em>= apiException&lt;<strong>ConstraintViolation</strong>, ErrorMessage&gt; {<strong><br></strong>    // more code here<br>}</pre><p>which in turns is used in the route definition (also posted above) and we come full circle:</p><pre>post&lt;Unit, ResponseAccount, RequestAccount&gt;(<br>    ...<br>    exceptions = <em>listOf</em>(<strong><em>badRequest</em></strong>),   <br>    ...<br>) {<br>    ...<br>}</pre><p>That’s it for part 3 of the series. If you enjoyed this, follow up with <a href="https://medium.com/p/52527ce3228">An opinionated Kotlin backend service — Database / Migration / ORM</a>.</p><p>As usual feel free to provide feedback. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e4b02aa6245" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An opinionated Kotlin backend service — Part 2]]></title>
            <link>https://1gravityllc.medium.com/an-opinionated-kotlin-backend-service-part-2-480ab5e6cdb2?source=rss-be8d858ab85c------2</link>
            <guid isPermaLink="false">https://medium.com/p/480ab5e6cdb2</guid>
            <dc:creator><![CDATA[Emanuel Moecklin]]></dc:creator>
            <pubDate>Wed, 28 Apr 2021 23:47:00 GMT</pubDate>
            <atom:updated>2021-05-07T18:09:21.922Z</atom:updated>
            <content:encoded><![CDATA[<h3>An opinionated Kotlin backend service - Build &amp; Deployment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*prcVa0xbVTFSB_ge" /></figure><p>This is the second part of my series on Kotlin based backend services.<br>If you missed the first part: <a href="https://medium.com/p/87f814e3dffd">An opinionated Kotlin backend service — Framework</a>.</p><h3>Gradle Build</h3><p>I had four main requirements for the build system:</p><ol><li>I wanted to use Gradle (not Maven)</li><li>Use a single language for code, configuration, build and deployment (as much as possible)</li><li>I wanted to manage plugin and dependency versions centrally</li><li>I wanted to support a mono repo approach with each backend service being a separate Gradle module</li></ol><p>Using Kotlin instead of Groovy supports the goal of using a single language for everything.</p><p>There are two main approaches to managing dependency versions centrally (instead of duplicating them in each module):</p><ul><li>Using the gradle.properties file</li><li>Using the <a href="https://docs.gradle.org/current/userguide/organizing_gradle_projects.html#sec:build_sources">buildSrc folder</a></li></ul><h4>Property file</h4><p>Define the versions in the top level <strong><em>gradle.properties</em></strong> file:</p><pre>kotlinVersion=1.4.32<br>ktorVersion=1.5.3</pre><p>For plugins use the <a href="https://docs.gradle.org/current/userguide/plugins.html">pluginManagement</a> function in the <strong><em>settings.gradle.kts</em></strong> file:</p><pre>pluginManagement {<br>    val kotlinVersion: String by settings<br>    plugins {<br>        kotlin(&quot;jvm&quot;) version kotlinVersion<br>    }<br>}</pre><p>The <strong><em>build.gradle.kts</em></strong> files will look like this:</p><pre>// Plugins<br>plugins <strong>{<br>    </strong>kotlin(&quot;jvm&quot;)   /// no version needed<br><strong>}</strong></pre><pre>/// Dependencies<br>val kotlinVersion: String by project<br>val ktorVersion: String by project</pre><pre>implementation(kotlin(&quot;stdlib&quot;, kotlinVersion))<br>implementation(&quot;io.ktor:ktor-server-core:$ktorVersion&quot;)</pre><h4><a href="https://docs.gradle.org/current/userguide/organizing_gradle_projects.html#sec:build_sources">buildSrc Folder</a></h4><p>This is my preferred approach since it supports my single <em>language to rule them all</em> approach.</p><p><em>buildSrc</em> is basically a special module that is compiled before any other module. Gradle automatically compiles and tests its code and puts it in the classpath of your build script.</p><p>For our purposes we only use it to manage dependencies and keep the module/service build files short and with little redundancy. All plugins and dependencies are managed in the two files <a href="https://github.com/1gravity/Ktor-Template/blob/main/buildSrc/src/main/kotlin/com/onegravity/Plugin.kt">Plugin.kt</a> and <a href="https://github.com/1gravity/Ktor-Template/blob/main/buildSrc/src/main/kotlin/com/onegravity/Dependency.kt">Dependency.kt</a>.</p><p>That way applying plugins and defining dependencies in each module becomes very simple:</p><pre>plugins {<br>    Plugin.modulePlugins.<em>forEach </em>{ (n, v) -&gt; id(n) <em>version </em>v }<br>}</pre><pre><em>dependencies </em>{<br>    Dependency.implementation.<em>forEach</em>(::implementation)<br>    Dependency.runtime.<em>forEach</em>(::runtimeOnly)<br>    Dependency.testImplementation.<em>forEach</em>(::testImplementation)<br>}</pre><h4><a href="https://gitlab.com/barfuin/gradle-taskinfo">TaskInfo</a></h4><p>I added TaskInfo as a Gradle plugin to display task dependencies and types. E.g. running ./gradlew tiTree assemble results in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*yQFfbOKHJQ2yiwZL9flRYQ.png" /></figure><h3>Containerization</h3><p>Dockerization is pretty much standard for today’s backend services and gives flexibility to deploy in almost any environment, local, on-premise, cloud, Kubernetes, OpenShift, you name it.</p><p>One of the challenges was to build the app in a container using Gradle. A lot of tutorials explain the process but most of them install the build tools as part of the build process, then build and then run the application (all in the same container).</p><p>I prefer to use a multi-stage build using one image for the build and another one to run the application. That way I can use a pre-configured image for the build without the need to install anything (reducing the build time = cost) and another one for the runtime environment. Separation of environments for build and runtime also seems to be a good approach security wise.</p><h4>Build</h4><pre>FROM gradle AS <em>build</em></pre><pre>WORKDIR /appbuild<br>COPY . /appbuild</pre><pre>RUN gradle wrapper     # better safe than sorry<br>RUN ./gradlew :account-service:clean :account-service:assemble</pre><h4>Deploy/Run</h4><p>The artifact from the build step is copied to the runtime container using the COPY command:</p><pre>FROM openjdk:8-jre-alpine<br><br>WORKDIR /app<br><br>COPY --from=<em>0 </em>appbuild/account-service/build/libs/account-service.jar application.jar<br><br>CMD [&quot;java&quot;, &quot;-server&quot;, &quot;-jar&quot;, &quot;application.jar&quot;]</pre><p>To build the runtime container use this command in the root directory of the project:</p><pre>DOCKER_BUILDKIT=1 docker build -f account-service/Dockerfile -t ktor-template/account .</pre><p>It will create an image with the tag <em>“ktor-template/account” (command docker images)</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*Ksu-dMHiNoPN-jA-qICTKw.png" /></figure><p>which can then be run using:</p><pre>docker run ktor-template/account</pre><h4>docker-compose</h4><p>While the template contains only a single service, my intention was (as mentioned above) to support a mono repo approach with multiple services in the same repository. Using docker-compose seemed a good way to manage multiple services (plus shared services like database, gateway, messaging services, monitoring etc.).</p><p>I don’t want to elaborate on the <em>docker-compose.yml</em> file here but will explain some of the details later in the series when I talk about the setup and integration of the database. Of interest at the moment is only how to start the application (which was already explained in part 1 of the series):</p><ul><li>in the root directory of the project run docker-compuse up (or sudo docker-compuse up)</li><li>Open <a href="http://localhost:2000/">http://localhost:2000</a></li></ul><p>That’s it for part 2 of the series. If you enjoyed this follow up with <a href="https://medium.com/p/1e4b02aa6245">An opinionated Kotlin backend service — API Routing and Documentation</a>.</p><p>As usual feel free to provide feedback. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=480ab5e6cdb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>