<?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 Alejandro Moya on Medium]]></title>
        <description><![CDATA[Stories by Alejandro Moya on Medium]]></description>
        <link>https://medium.com/@ar.demon?source=rss-949231236245------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ja5w9h6Ue_RymaYWnVfUYQ.jpeg</url>
            <title>Stories by Alejandro Moya on Medium</title>
            <link>https://medium.com/@ar.demon?source=rss-949231236245------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 00:09:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ar.demon/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[Consuming a KMP dependency on iOS using SPM]]></title>
            <link>https://medium.com/teamsnap-engineering/consuming-a-kmp-dependency-on-ios-using-spm-c45c343e406b?source=rss-949231236245------2</link>
            <guid isPermaLink="false">https://medium.com/p/c45c343e406b</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kmp]]></category>
            <category><![CDATA[spm]]></category>
            <dc:creator><![CDATA[Alejandro Moya]]></dc:creator>
            <pubDate>Tue, 05 Sep 2023 13:22:35 GMT</pubDate>
            <atom:updated>2023-09-05T13:22:35.658Z</atom:updated>
            <content:encoded><![CDATA[<p>In our previous post, <a href="https://medium.com/teamsnap-engineering/consuming-a-private-kmp-dependency-from-github-f91264346879">consuming a Private KMP dependency from GitHub</a>, we explained how to consume the iOS version of the KMP library using cocoapods. After writing that post and before writing <a href="https://medium.com/teamsnap-engineering/the-kmp-implementation-at-teamsnap-6b8b146f003f">The KMP implementation at TeamSnap</a> we switched to using SPM as we want to stop using `cocoapods`. An attentive reader pointed this out, and since we want to help everyone in the community that would need it, here we go!</p><p>If you went through <a href="https://medium.com/teamsnap-engineering/setting-up-a-kmp-shared-library-5f596afc6e09">Setting up a KMP shared library</a> there are 2 sections that talk about configuring the specifics of the library compilation, one is the version catalogs and the other is the gradle scripts, we didn’t cover the iOS `cocoapods` configuration on the version catalogs as we wanted to give you the freedom of being able to put what you like on catalogs and what you prefer to have on the scripts.</p><p>In this post we are going to use version catalogs as they are now a supported feature on Android Studio since Giraffe.</p><h4>Version catalogs</h4><p>We are going to add a new version catalog file named strings.versions.toml . Below is an example of the catalog contents:</p><pre>[versions]<br><br>ios-summary = &quot;My library&quot;<br>ios-authors = &quot;My company&quot;<br>ios-homepage = &quot;https://myhomepage.com/path&quot;<br>ios-deployment-target = &quot;14.0&quot;<br>ios-basename = &quot;MySharedLibrary&quot;<br></pre><p>You can add any text definition on this file that would be used on the scripts, this will reduce having fixed texts on the scripts.</p><h4>Gradle scripts</h4><p>Don’t forget to add this new version catalog to the list that you have on settings.gradle.kts at the project root:</p><pre>dependencyResolutionManagement {<br>...<br>  versionCatalogs {<br>    ...<br>    create(&quot;strings&quot;) {<br>      from(files(&quot;./catalogs/strings.versions.toml&quot;)<br>    }<br>    ...<br>  }<br>  ...<br>}</pre><p>Now sync your Gradle files and you should have the new version catalog available.</p><p>Now we can add the configuration from the version catalog to the required places, open build.gradle.kts on the shared module, in the Kotlin section you’ll find this or something similar:</p><pre>kotlin {<br>  ...<br>  configure(listOf(iosX64, iosArm64, iosSim)) {<br>    binaries {<br>      framework {<br>        // Any dependecy you add for ios should be added here using export()<br>        export(commonlibs.kotlin.stdlib)<br>        xcf.add(this)<br>      }<br>    }<br>  }<br>  ...<br>  cocoapods {<br>    val iosDefinitions = commonlibs.versions.ios<br>    name = iosDefinitions.basename.get()<br>    summary = iosDefinitions.summary.get()<br>    homepage = iosDefinitions.homepage.get()<br>    authors = iosDefinitions.authors.get()<br>    version = commonlibs.versions.library.version.get()<br>    ios.deploymentTarget = iosDefinitions.deployment.target.get()<br>    framework {<br>      baseName = iosDefinitions.basename.get()<br>      isStatic = false<br>      transitiveExport = true<br>      embedBitcode(BITCODE)<br>    }<br>    specRepos {<br>      url(https://medium.com/&quot;https://github.com/user/repo.git&quot;) // Use your repo here<br>    }<br>    publishDir = rootProject.file(&quot;./&quot;)<br>  }<br>  ...<br>}<br></pre><p>This previous snippet is part of what we left as an example on the previous post but we didn’t dive into the specifics of the configuration, this is the new setup:</p><pre>kotlin {<br>  val iosStrings = strings.versions.ios<br>  ...<br>  configure(listOf(iosX64, iosArm64, iosSim)) {<br>    binaries {<br>      framework {<br>        // Any dependecy you add for ios should be added here using export()<br>        export(commonlibs.kotlin.stdlib)<br>        xcf.add(this)<br>        baseName = iosStrings.basename<br>      }<br>    }<br>  }<br>  ...<br>  cocoapods {<br>    name = iosStrings.basename.get()<br>    summary = iosStrings.summary.get()<br>    homepage = iosStrings.homepage.get()<br>    authors = iosStrings.authors.get()<br>    version = commonlibs.versions.library.version.get()<br>    ios.deploymentTarget = iosStrings.deployment.target.get()<br>    framework {<br>      baseName = iosStrings.basename.get()<br>      isStatic = false<br>      transitiveExport = true<br>      embedBitcode(BITCODE)<br>    }<br>    specRepos {<br>      url(https://medium.com/&quot;https://github.com/user/repo.git&quot;) // Use your repo here<br>    }<br>    publishDir = rootProject.file(&quot;./&quot;)<br>  }<br>  ...<br>}</pre><p>We switched to the new strings catalog and also applied the existing configurations, but we also added a new one on the binaries.framework section, as you can see, you have 3 places that share the same configuration:</p><ol><li>binaries.framework.basename</li><li>cocoapods.name</li><li>cocoapods.framework.basename</li></ol><p>It’s important to sync these names, otherwise, the library won’t compile and you would also find difficult to know the name of the framework package.</p><p>Now once you process the release the library should be available on your repo as MySharedLibrary.xcframework , with your podspec file as usual.</p><p>Now, let’s create the Package.swift file to enable SPM to look for the framework binary:</p><pre>// swift-tools-version: 5.6<br>// The swift-tools-version declares the minimum version of Swift<br>// required to build this package.<br>import PackageDescription<br><br>let package = Package(<br>  name: &quot;MySharedLibrary&quot;,<br>  platforms: [.iOS(.v14)],<br>  products: [<br>    .library(<br>      name: &quot;MySharedLibrary&quot;,<br>      targets: [&quot;MySharedLibrary&quot;]<br>    ),<br>  ],<br>  dependencies: [],<br>  targets: [<br>    .binaryTarget(name: &quot;MySharedLibrary&quot;,<br>            path: &quot;./MySharedLibrary.xcframework&quot;),<br>  ]<br>)</pre><p>Save Package.swift at the root of the project/repo, push the changes and release a new version of your library. This first version that contains the Package.swift file will be visible to SPM.</p><p>Now remove the cocoapods setup for the library on your ios project by removing the dependency on the podfile and running pod install. After this, on Xcode, go to File -&gt; Add packages, on the search field paste the url of your private git repo, it will ask you for your github credentials if you didn’t add them, it would be a good idea to add them on the Xcode settings prior to doing it as this prevents any issue on installing and updating the library later, this won’t be a problem on the CI as it will use the existing git configuration. You should see the package available in the list of packages, set the dependency rule to either exact version or to any desired version tag range setting, don’t use commit or branch as you already release the library using version tags. Set the minimum or exact version to the one you just processed and set the add to project option to the project you had setup the library using cocoapods previously. Now hit the Add package button and enjoy consuming the KMP library from SPM.</p><p>As you might have guessed, the most important thing is to set the library basename, use that on the Package.swift file and release a version that contains this package file on the repo. Once you do all this, you’ll have an SPM compatible library, and the best of all is that this is a binary libary, the package file is set to consume the library as a binary target and you will get it in that way on the project, no need to compile the sources again and again!.</p><p>We love sharing the knowledge we got from implementing KMP with the community, if you have any question just leave a comment and we will give our best to answer them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c45c343e406b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/teamsnap-engineering/consuming-a-kmp-dependency-on-ios-using-spm-c45c343e406b">Consuming a KMP dependency on iOS using SPM</a> was originally published in <a href="https://medium.com/teamsnap-engineering">TeamSnap Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The KMP implementation at TeamSnap]]></title>
            <link>https://medium.com/teamsnap-engineering/the-kmp-implementation-at-teamsnap-6b8b146f003f?source=rss-949231236245------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b8b146f003f</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kmp]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Alejandro Moya]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 17:49:57 GMT</pubDate>
            <atom:updated>2023-08-24T17:49:57.288Z</atom:updated>
            <content:encoded><![CDATA[<p>On previous posts we explained how to <a href="https://medium.com/teamsnap-engineering/setting-up-a-kmp-shared-library-5f596afc6e09">setup a KMP library</a> and <a href="https://medium.com/teamsnap-engineering/consuming-a-private-kmp-dependency-from-github-f91264346879">consume it from our iOS and Android projects</a>. Now we are going to show you some details on the TeamSnap implementation, as we are moving our business logic to KMP in small steps and without breaking the existing codebase in the process.</p><p>Our original codebase is, as with many of the native apps that we can find in the app stores on Android and iOS, built using the respective SDKs. This means that we have a project for each platform, and each project has it’s own codebase. While the UX on each platform could be different as the standards differ, the business logic is the same, the connection to the backend, the business logic, the databases and objects we use to handle all the UX interactions, everything under the hood is or could be the same.</p><p>In cross-platform there are different options for building mobile apps. You have frameworks that use html and other web languages to build these apps and you also have frameworks that use native solutions to build them. We prefer to stay native, to avoid consuming more resources on the users device, and since we want to keep the experience on each platform as close to the UX standards as possible, we found that keeping our existing projects for the UX would be ideal, and merging the business logic into one codebase would be the wise move. Compared to other solutions, KMP was an easy choice. Here are a few reasons why:</p><p>Flexibility on the implementation:</p><ul><li>You can choose to implement any part of your business logic or even go full cross-platform with KMP.</li><li>You can start a new project or integrate the KMP project in different ways on your existing projects.</li><li>You can build common and specific platform code on the KMP project.</li></ul><p>Language benefits:</p><ul><li>On KMP you can reuse much of the Android code on KMP, meaning that you will find yourself often just copy/pasting your existing Android code.</li><li>Similarities with Swift make the learning curve more friendly for iOS developers.</li></ul><p>Performance:</p><ul><li>For Android a KMP library is just a regular Android library, no extra integrations needed.</li><li>For iOS a KMP library is an Objective C compiled library with Swift friendly implementations. In some cases we might have to add a few extra dependencies to implement cool features, but nothing we don’t usually do on native coding.</li><li>One more thing to note on the performance side is that on iOS the perceived performance is superior to other solutions.</li></ul><p>So, we originally had our projects setup in the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rkeRGGRqkk5VqTtiZaJ2Vw.png" /></figure><p>Each with their own repository, each with their own codebase.</p><p>One of the issues when making a decision about an existing codebase is how many changes you’ll have to make to integrate something on your existing architecture, and also, you don’t want to degrade the UX and the development experience. If you have to build an entire new codebase or move your current codebase in one step, that would probably result in many issues for both, end users and developers.</p><p>This is why we started slowly, in fact we started by just adding some constants on the shared codebase. Our own experience showed us that the best is always to start on the smallest possible project you can take to share code, and the smallest thing would be just a few constants that would be used on both platforms. It’s even better if these constants are new, something you didn’t have previously.</p><p>After that you can start by adding the new architecture you want to implement, always in small steps, do not try to go full Jedi mode on the first pass, it’s like building your new dream home in the same grounds of your existing one (For the home renovations shows fans).</p><p>Another thing you need when starting a shared codebase is to have all the team involved, everyone needs to review these changes, the more eyes the better. Make sure that at least one Android and iOS developer are looking at the new code, and make as many iterations as needed to check that the changes are accepted and working on both platforms, this will ensure the success of the new implementation.</p><p>After these initial iterations we were able to add the foundations of the new architecture and started to implement small pieces of business logic, now we can take bigger projects that will live on the shared codebase and also start to migrate the code we need from the specific platforms.</p><p>The final result is keeping our original projects intact, nothing changes there, except a few helper methods or new external dependencies. The new codebase has its own repository, much like any other external dependency we could consume like Alamofire on iOS or Retrofit on Android. This also makes the implementation on each platform more flexible as each platform team could be working on different features and could use different versions of the shared library.</p><p>You could be asking - what’s the final result?, well, the graphic below shows the target goal for our KMP implementation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QpPhvK-dRmW3QUDDXpe2Tw.png" /></figure><p>We are far from reaching this stage, but we started and all the team is excited about making these changes. As you can see, the original projects and repositories still exist, but the business logic, cache and network moves to the new repository. We still leave some specific business logic on each platform, and this is expected. One advantage in this is that we can take the best of each platform and move it to the new shared codebase, also, as this new codebase does not contain any UI code, we can add as many unit tests as we like, code coverage was never that easy. Working on a big project that contains UI and business logic tends to make code coverage a problem, the same happens with clean coding practices, you have so many things mixed that you lose track at some point. This new approach helps reduce the mix by completely separating things and also helps to review and optimize the original codebases by moving the best parts and reducing the amount of code.</p><p>Another benefit for us developers is the infamous compilation time, when you have all your code on the same project, you have to compile everything, it doesn’t matter if the code didn’t change, the compiler still has to evaluate if things changed. That takes time, and moving the code to a compiled library reduces compilation time in big numbers. Each piece of code you move to the shared codebase will get compiled for both platforms once, after that, when you consume them on each platform, you won’t need to compile them again.</p><p>We will share more KMP goodies in the future. Stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b8b146f003f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/teamsnap-engineering/the-kmp-implementation-at-teamsnap-6b8b146f003f">The KMP implementation at TeamSnap</a> was originally published in <a href="https://medium.com/teamsnap-engineering">TeamSnap Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Consuming a Private KMP dependency from github]]></title>
            <link>https://medium.com/teamsnap-engineering/consuming-a-private-kmp-dependency-from-github-f91264346879?source=rss-949231236245------2</link>
            <guid isPermaLink="false">https://medium.com/p/f91264346879</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kmm]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Alejandro Moya]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 14:02:01 GMT</pubDate>
            <atom:updated>2023-08-07T14:02:01.699Z</atom:updated>
            <content:encoded><![CDATA[<h3>Consuming a Private KMP dependency from GitHub</h3><p>Our previous post explained how to create a private KMP library on github without having to share the same repository for the Android and iOS project. This wouldn’t be complete without explaining how to consume the library from each platform. Well, this post will give you the configuration needed for the Android and iOS project to work.</p><h3>The Android configuration</h3><p>On the root build.gradle or build.gradle.kts you’ll find the repositories:</p><pre>allProjects {<br>  repositories {<br>    google()<br>    mavenCentral()<br>    ...<br>    }<br>}</pre><p>We need to add the private maven repo there:</p><ul><li>build.gradle.kts :</li></ul><pre>allprojects {<br>    repositories {<br>        ...<br>        maven {<br>            url = URI(&quot;https://maven.pkg.github.com/USER/REPO&quot;)<br>            credentials {<br>                username = System.getenv(&quot;MYUSER&quot;)<br>                password = System.getenv(&quot;MYPAT&quot;)<br>            }<br>        }<br>    }<br>}</pre><ul><li>build.gradle :</li></ul><pre>allprojects {<br>    repositories {<br>        ...<br>        maven {<br>            url &#39;https://maven.pkg.github.com/USER/REPO&#39;<br>            credentials {<br>                username = &quot;${System.getenv(&quot;MYUSER&quot;)}&quot;<br>                password = &quot;${System.getenv(&quot;MYPAT&quot;)}&quot;<br>            }<br>        }<br>    }<br>}</pre><p>As you can see on the scripts again, we see the MYUSER and MYPAT environment variables, each user will add these to their computer with their own github user and private access token with access to the private repo.</p><p>This works for mac, windows and linux, as long as the user adds the environment variables to their system environment variables configuration, they will have access to the repo.</p><p>After this, they can add the library as a regular dependency using api or implementation , depending on how you set the package name it should look like this:</p><pre>implementation(&quot;com.example.mylibrary:shared-android:0.0.1&quot;)</pre><p>This finishes the Android project configuration.</p><h3>The iOS project configuration</h3><p>There are a few options available on mac to achieve the same behaviour, you could use the same approach as on Android by using the environment variables, I’ve used that option in the past, but there’s a catch if you have a project that runs on CI. using environment variables on cocoapods exposes the information on the console output. This is due to cocoapods using git commands to retrieve the dependencies from each repo.</p><p>So, which option is better for cocoapods?</p><p>The answer is git credentials. And how?</p><p>The answer is a terminal command:</p><pre>git config --global credential.helper store</pre><p>After running this command, you can add the dependency to your pod file as any other regular dependency, in the case of the KMP library you would use the name and basename parameters under the cocoapods configuration on the gradle script file:</p><pre>pod &#39;MySharedLibrary&#39;, :git =&gt; &#39;https://github.com/USER/REPO.git&#39;, :tag =&gt; &#39;0.0.1&#39;</pre><p>Once you add this to the pod file and save it you can run pod install as usual, you’ll get asked about the credentials, once you complete the credentials those will be saved for git to use them in the future. Remember you can’t use your password on git, you’ll have to create a PAT to be able to use this feature.</p><p>Well, that completes the configuration, you can now consume your KMP library from Android and iOS, you can keep working on your projects as usual, and you can now share a codebase that is built as native libraries for each platform. We at TeamSnap use this successfully and each mobile platform team enjoys the benefits of having a single codebase for some of our architecture. As always, leave your comments and we’ll read and answer as we can.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f91264346879" width="1" height="1" alt=""><hr><p><a href="https://medium.com/teamsnap-engineering/consuming-a-private-kmp-dependency-from-github-f91264346879">Consuming a Private KMP dependency from github</a> was originally published in <a href="https://medium.com/teamsnap-engineering">TeamSnap Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up a KMP shared library]]></title>
            <link>https://medium.com/teamsnap-engineering/setting-up-a-kmp-shared-library-5f596afc6e09?source=rss-949231236245------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f596afc6e09</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alejandro Moya]]></dc:creator>
            <pubDate>Tue, 01 Aug 2023 18:38:40 GMT</pubDate>
            <atom:updated>2023-08-01T18:38:40.034Z</atom:updated>
            <content:encoded><![CDATA[<p>Long time no see my fellowship 😉. It’s been a while, but I have something I think many will like to read and apply to their own projects.</p><p>At TeamSnap we started using KMP (Kotlin Multiplatform) to share some common code between mobile platforms, keeping everything native so that our users enjoy the best performance on their apps. While the usual tutorials from the lords of the Jetbrains (see what I did there?) and other sources explain how to create an entire mobile project using KMP, or having the code for each platform on the same repo, this one will show you several things like, creating an independent KMP shared library, also to consume it from your existing Android and iOS projects as if it was any other regular dependency, and to top it all, to have all this done on a private repository on GitHub with tests, code coverage and publish actions; yes, it’s a lot, but this setup makes things a lot easier than having to create an entire new project or reorganize everything to have it on the same repo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*gRB4_gT8gHLnIaG3j7e4GQ.jpeg" /></figure><p>We are going to divide this post into 5 sections to have clear steps for the setup:</p><ol><li>Create the project.</li><li>Version Catalogs</li><li>Gradle Scripts</li><li>Tests Action</li><li>Publish Action</li></ol><p>Ok, let’s start by explaining the existing setup, you already have an iOS and Android project, each has its own repo, the ios project is using cocoapods for dependencies, the Android project uses the good ol’ maven/gradle for the same purpose. This is not going to change, the idea behind this setup is that nothing changes on the existing projects, this makes the initial integration far lighter, making all the developers in the team happier.</p><h3>Create the project</h3><p>Now, let’s create the KMP shared library by using <a href="https://developer.android.com/studio">Android Studio</a>:</p><ul><li>Install the <a href="https://plugins.jetbrains.com/plugin/14936-kotlin-multiplatform-mobile">KMP plugin</a></li><li>Install the <a href="https://plugins.jetbrains.com/plugin/8195-toml">TOML plugin</a></li><li>Make sure you are using at least Android Studio Flamingo and kotlin 1.8.20 as that will ensure the best feature set available for both platforms.</li><li>Create a new project:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*g3E83tsgnb5RJzF3svYRAQ.png" /></figure><ul><li>Select the Kotlin Multiplatform Library</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*yZU8bKiLcMSlfAW9NhURUg.png" /></figure><ul><li>Configure the basics</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IGHIFJTjH2mRMSbAXQRsOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IfIlnX53eWNUzxoVXzOYmQ.png" /></figure><ul><li>Once you finish the assistant you should have this folder structure:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*QGCUt5Az70XB2ip486cplg.png" /></figure><p>This is the basic project setup, it will leave you with a KMP library that could be built for iOS and Android, but we need more, we need to publish this library somewhere we can consume from on our iOS and Android projects. So, let’s start with the project configuration:</p><p>Lets check the gradle.properties file, it should look like the following:</p><pre>#Gradle<br>org.gradle.jvmargs=-Xmx2048M -Dfile.encoding=UTF-8 -Dkotlin.daemon.jvm.options\=&quot;-Xmx2048M&quot;<br>org.gradle.java.installations.fromEnv=JDK_17<br>org.gradle.configureondemand=true<br>org.gradle.daemon=true<br>org.gradle.parallel=true<br>org.gradle.workers.max=8<br>java.mainToolchainVersion=17<br>java.modularToolchainVersion=17<br><br>#Kotlin<br>kotlin.code.style=official<br><br>#Android<br>android.useAndroidX=true<br>android.nonTransitiveRClass=true<br><br>#MPP<br>kotlin.mpp.enableCInteropCommonization=true<br>kotlin.mpp.androidSourceSetLayoutVersion=2</pre><p>We are using java 17, setting parallel builds enabled, also we are using the new Android source set layout. With this you finished creating the project.</p><h3>The Version Catalogs</h3><p>First we will configure the project to use catalog files (<a href="https://docs.gradle.org/current/userguide/platforms.html">here is the official documentation</a>), these files help reduce the boilerplate on the script files by moving dependencies out of them and into a dedicated file that will contain groups of libraries with versions.</p><p>You’ll create a directory on the root of the project, in our case we named it catalogs, and inside this you’ll create a file named common.versions.toml, you’ll open this file and add the required libraries and versions for your project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*Yg-Bc71d8VWrYxHhz7ePhA.png" /></figure><pre>[versions]<br>library-group = &quot;com.my.library&quot;<br>library-version = &quot;0.0.1&quot;<br>android = &quot;8.0.2&quot;<br>kotlin = &quot;1.8.20&quot;<br>kover = &quot;0.6.1&quot;<br>ksp = &quot;1.8.20-1.0.11&quot;<br><br>[libraries]<br>kotlin-stdlib = { module = &quot;org.jetbrains.kotlin:kotlin-stdlib-common&quot;, version.ref = &quot;kotlin&quot; }<br><br>[plugins]<br>multiplatform = { id = &quot;org.jetbrains.kotlin.multiplatform&quot;, version.ref = &quot;kotlin&quot; }<br>kotlin-android = { id = &quot;org.jetbrains.kotlin.android&quot;, version.ref = &quot;kotlin&quot; }<br>android-lib = { id = &quot;com.android.library&quot;, version.ref = &quot;android&quot; }<br>android-app = { id = &quot;com.android.application&quot;, version.ref = &quot;android&quot; }<br>kover = { id = &quot;org.jetbrains.kotlinx.kover&quot;, version.ref = &quot;kover&quot; }</pre><p>We left an example of the basics needed to have the project build, you can extend this by adding several multiplatform libraries, <a href="https://github.com/terrakok/kmm-awesome">here’s a link to a list of handy KMP libraries</a>.</p><p>Now you need to import this catalog on the gradle scripts. On the root of your project you’ll find a file named settings.gradle.kts , open the file and add the following snippet:</p><pre>dependencyResolutionManagement {<br>    repositories {<br>        google()<br>        mavenCentral()<br>    }<br>    versionCatalogs {<br>        create(&quot;commonlibs&quot;) {<br>            from(files(&quot;./catalogs/common.versions.toml&quot;))<br>        }<br>    }<br>}</pre><p>The versionCatalogs block imports common.versions.toml with the commonLibs name, you will use this name to access every dependency saved on this catalog. With that you have the version catalogs done!.</p><h3>Gradle Scripts</h3><p>We are getting closer to have a working KMP project. Before we get to add our code we need to setup the gradle scripts to be able to compile, test and release versions of our library, we’ll cover this configuration here.</p><p>We created this project and added the catalog files, we can commit the changes to our github repo and continue. We tried to break the post in short chunks of configurations to allow you to do this, as this will help you get things done separately and in well defined steps, the git history would also be clean and well defined. Are you feeling like this?:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl3vR7aXoQX0OdHi48%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl3vR7aXoQX0OdHi48%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl3vR7aXoQX0OdHi48%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f3bbb5ca430a6f7f81a3d9868124c88/href">https://medium.com/media/8f3bbb5ca430a6f7f81a3d9868124c88/href</a></iframe><p>Now we will open the build.gradle.kts file located at the root of the project and will change a few things.</p><pre>plugins {<br>    //trick: for the same plugin versions in all sub-modules<br>    id(&quot;com.android.library&quot;).version(&quot;8.0.2&quot;).apply(false)<br>    kotlin(&quot;multiplatform&quot;).version(&quot;1.8.21&quot;).apply(false)<br>}<br><br>tasks.register(&quot;clean&quot;, Delete::class) {<br>    delete(rootProject.buildDir)<br>}</pre><p>This is the original code, or something similar… we will use the version catalog we created to make it look like this:</p><pre>@Suppress(&quot;DSL_SCOPE_VIOLATION&quot;)<br>plugins {<br>    alias(commonlibs.plugins.multiplatform).apply(false)<br>    alias(commonlibs.plugins.kotlin.android).apply(false)<br>    alias(commonlibs.plugins.android.lib).apply(false)<br>    alias(commonlibs.plugins.android.app).apply(false)<br>    alias(commonlibs.plugins.kover).apply(false)<br>}<br><br>tasks.register(&quot;clean&quot;, Delete::class) {<br>    delete(rootProject.buildDir)<br>}<br><br>subprojects {<br>    afterEvaluate {<br>        tasks.withType&lt;org.jetbrains.kotlin.gradle.tasks.KotlinCompile&gt; {<br>            kotlinOptions {<br>                jvmTarget = JavaVersion.VERSION_17.toString()<br>            }<br>        }<br>    }<br>}</pre><p>Since we are using version catalogs the plugins block changes a little, we are also making the jvmTarget use the 17 version. We added a suppress for a <a href="https://youtrack.jetbrains.com/issue/KTIJ-19369/False-positive-cant-be-called-in-this-context-by-implicit-receiver-with-plugins-in-Gradle-version-catalogs-as-a-TOML-file">known bug</a> when using version catalogs with toml files.</p><p>Now we will change the shared project gradle script, here’s the original:</p><pre>plugins {<br>    kotlin(&quot;multiplatform&quot;)<br>    kotlin(&quot;native.cocoapods&quot;)<br>    id(&quot;com.android.library&quot;)<br>}<br><br>@OptIn(org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi::class)<br>kotlin {<br>    targetHierarchy.default()<br>    android {<br>        compilations.all {<br>            kotlinOptions {<br>                jvmTarget = &quot;1.8&quot;<br>            }<br>        }<br>    }<br>    iosX64()<br>    iosArm64()<br>    iosSimulatorArm64()<br>    cocoapods {<br>        summary = &quot;Some description for the Shared Module&quot;<br>        homepage = &quot;Link to the Shared Module homepage&quot;<br>        version = &quot;1.0&quot;<br>        ios.deploymentTarget = &quot;14.1&quot;<br>        framework {<br>            baseName = &quot;shared&quot;<br>        }<br>    }<br>    <br>    sourceSets {<br>        val commonMain by getting {<br>            dependencies {<br>                //put your multiplatform dependencies here<br>            }<br>        }<br>        val commonTest by getting {<br>            dependencies {<br>                implementation(kotlin(&quot;test&quot;))<br>            }<br>        }<br>    }<br>}<br>android {<br>    namespace = &quot;com.example.mylibrary&quot;<br>    compileSdk = 33<br>    defaultConfig {<br>        minSdk = 27<br>    }<br>}</pre><p>These are the changes:</p><pre>@file:Suppress(&quot;UnstableApiUsage&quot;)<br>import org.jetbrains.kotlin.gradle.plugin.mpp.BitcodeEmbeddingMode.BITCODE<br>import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget<br>import org.jetbrains.kotlin.gradle.plugin.mpp.apple.XCFramework<br>import org.gradle.api.tasks.testing.logging.TestExceptionFormat<br><br>plugins {<br>    kotlin(&quot;multiplatform&quot;)<br>    kotlin(&quot;native.cocoapods&quot;)<br>    id(&quot;maven-publish&quot;)<br>    id(&quot;kover&quot;)<br>}<br><br>group = commonlibs.versions.library.group.get()<br>version = commonlibs.versions.library.version.get()<br><br>var androidTarget: String = &quot;&quot;<br><br>kotlin {<br>    val android = android {<br>        publishLibraryVariants(&quot;release&quot;)<br>    }<br>    androidTarget = android.name<br>    val xcf = XCFramework()<br>    val iosX64 = iosX64()<br>    val iosArm64 = iosArm64()<br>    val iosSim = iosSimulatorArm64()<br>    configure(listOf(iosX64, iosArm64, iosSim)) {<br>        binaries {<br>            framework {<br>                //Any dependecy you add for ios should be added here using export()<br>                export(commonlibs.kotlin.stdlib)<br>                xcf.add(this)<br>            }<br>        }<br>    }<br><br>    targets.withType&lt;KotlinNativeTarget&gt; {<br>        binaries.all {<br>            freeCompilerArgs += listOf(&quot;-Xgc=cms&quot;)<br>        }<br>    }<br><br>   cocoapods {<br>        val iosDefinitions = commonlibs.versions.ios<br>        name = iosDefinitions.basename.get()<br>        summary = iosDefinitions.summary.get()<br>        homepage = iosDefinitions.homepage.get()<br>        authors = iosDefinitions.authors.get()<br>        version = commonlibs.versions.library.version.get()<br>        ios.deploymentTarget = iosDefinitions.deployment.target.get()<br>        framework {<br>            baseName = iosDefinitions.basename.get()<br>            isStatic = false<br>            transitiveExport = true<br>            embedBitcode(BITCODE)<br>        }<br>        specRepos {<br>            url(https://medium.com/&quot;https://github.com/user/repo.git&quot;) //use your repo here<br>        }<br>        publishDir = rootProject.file(&quot;./&quot;)<br>    }<br><br>    sourceSets {<br>        val commonMain by getting {<br>            dependencies {<br>                api(commonlibs.kotlin.stdlib)<br>            }<br>        }<br>        val commonTest by getting {<br>            dependencies {<br>                implementation(kotlin(&quot;test-common&quot;))<br>                implementation(kotlin(&quot;test-annotations-common&quot;))<br>            }<br>        }<br>        val androidMain by getting {<br>            dependencies {<br>                //Add your specific android dependencies here<br>            }<br>        }<br>        val androidUnitTest by getting {<br>            dependsOn(androidMain)<br>            dependsOn(commonMain)<br>            dependencies {<br>                implementation(kotlin(&quot;test-junit&quot;))<br>                //you should add the android junit here<br>            }<br>        }<br>        val iosX64Main by getting<br>        val iosArm64Main by getting<br>        val iosSimulatorArm64Main by getting<br>        val iosMain by creating {<br>            dependsOn(commonMain)<br>            iosX64Main.dependsOn(this)<br>            iosArm64Main.dependsOn(this)<br>            iosSimulatorArm64Main.dependsOn(this)<br>            dependencies {<br>                //Add any ios specific dependencies here, remember to also add them to the export block<br>            }<br>        }<br>        val iosX64Test by getting<br>        val iosArm64Test by getting<br>        val iosSimulatorArm64Test by getting<br>        val iosTest by creating {<br>            dependsOn(commonTest)<br>            iosX64Test.dependsOn(this)<br>            iosArm64Test.dependsOn(this)<br>            iosSimulatorArm64Test.dependsOn(this)<br>        }<br>    }<br>}<br><br>android {<br>    namespace = commonlibs.versions.library.group.get()<br>    compileSdk = //create your own android versions catalog and add this version there<br>    defaultConfig {<br>        minSdk = //same as with compileSdk<br>        targetSdk = //same as with compileSdk<br>    }<br>    sourceSets[&quot;main&quot;].manifest.srcFile(&quot;src/androidMain/AndroidManifest.xml&quot;)<br>    beforeEvaluate {<br>        libraryVariants.all {<br>            compileOptions {<br>                // Flag to enable support for the new language APIs<br>                isCoreLibraryDesugaringEnabled = true<br>                sourceCompatibility = JavaVersion.VERSION_17<br>                targetCompatibility = JavaVersion.VERSION_17<br>            }<br>        }<br>    }<br>    dependencies {<br>        coreLibraryDesugaring(...)//same as with compileSdk<br>    }<br>    publishing {<br>        singleVariant(&quot;release&quot;) {<br>            withSourcesJar()<br>            withJavadocJar()<br>        }<br>    }<br>    testOptions {<br>        unitTests.isReturnDefaultValues = true<br>    }<br>}<br><br>publishing {<br>    repositories {<br>        maven {<br>            name = &quot;github&quot;<br>            url = uri(&quot;https://maven.pkg.github.com/user/repo&quot;)<br>            credentials {<br>                username = System.getenv()[&quot;MYUSER&quot;]<br>                password = System.getenv()[&quot;MYPAT&quot;]<br>            }<br>        }<br>    }<br>    val thePublications = listOf(androidTarget) + &quot;kotlinMultiplatform&quot;<br>    publications {<br>        matching { it.name in thePublications }.all {<br>            val targetPublication = this@all<br>            tasks.withType&lt;AbstractPublishToMaven&gt;()<br>                .matching { it.publication == targetPublication }<br>                .configureEach { onlyIf { findProperty(&quot;isMainHost&quot;) == &quot;true&quot; } }<br>        }<br>        matching { it.name.contains(&quot;ios&quot;, true) }.all {<br>            val targetPublication = this@all<br>            tasks.withType&lt;AbstractPublishToMaven&gt;()<br>                .matching { it.publication == targetPublication }<br>                .forEach { it.enabled = false }<br>        }<br>    }<br>}<br><br>afterEvaluate {<br>    tasks.named(&quot;podPublishDebugXCFramework&quot;) {<br>        enabled = false<br>    }<br>    tasks.named(&quot;podSpecDebug&quot;) {<br>        enabled = false<br>    }<br>    tasks.withType&lt;JavaCompile&gt;().configureEach {<br>        sourceCompatibility = JavaVersion.VERSION_17.toString()<br>        targetCompatibility = JavaVersion.VERSION_17.toString()<br>    }<br>    tasks.withType&lt;AbstractTestTask&gt;().configureEach {<br>        testLogging {<br>            exceptionFormat = TestExceptionFormat.FULL<br>            events(&quot;started&quot;, &quot;skipped&quot;, &quot;passed&quot;, &quot;failed&quot;)<br>            showStandardStreams = true<br>        }<br>    }<br>}<br><br>val buildIdAttribute = Attribute.of(&quot;buildIdAttribute&quot;, String::class.java)<br>configurations.forEach {<br>    it.attributes {<br>        attribute(buildIdAttribute, it.name)<br>    }<br>}<br><br>val moveIosPodToRoot by tasks.registering {<br>    group = &quot;myGroup&quot;<br>    doLast {<br>        val releaseDir = rootProject.file(<br>            &quot;./release&quot;<br>        )<br>        releaseDir.copyRecursively(<br>            rootProject.file(&quot;./&quot;),<br>            true<br>        )<br>        releaseDir.deleteRecursively()<br>    }<br>}<br><br>tasks.named(&quot;podPublishReleaseXCFramework&quot;) {<br>    finalizedBy(moveIosPodToRoot)<br>}<br><br>val publishPlatforms by tasks.registering {<br>    group = &quot;myGroup&quot;<br>    dependsOn(<br>        tasks.named(&quot;publishAndroidReleasePublicationToGithubRepository&quot;),<br>        tasks.named(&quot;podPublishReleaseXCFramework&quot;)<br>    )<br>    doLast {<br>        exec { commandLine = listOf(&quot;git&quot;, &quot;add&quot;, &quot;-A&quot;) }<br>        exec { commandLine = listOf(&quot;git&quot;, &quot;commit&quot;, &quot;-m&quot;, &quot;iOS binary lib for version ${commonlibs.versions.library.version.get()}&quot;) }<br>        exec { commandLine = listOf(&quot;git&quot;, &quot;push&quot;, &quot;origin&quot;, &quot;main&quot;) }<br>        exec { commandLine = listOf(&quot;git&quot;, &quot;tag&quot;, commonlibs.versions.library.version.get()) }<br>        exec { commandLine = listOf(&quot;git&quot;, &quot;push&quot;, &quot;--tags&quot;) }<br>        println(&quot;version ${commonlibs.versions.library.version.get()} built and published&quot;)<br>    }<br>}<br><br>val compilePlatforms by tasks.registering {<br>    group = &quot;myGroup&quot;<br>    dependsOn(<br>        tasks.named(&quot;compileKotlinIosArm64&quot;),<br>        tasks.named(&quot;compileKotlinIosX64&quot;),<br>        tasks.named(&quot;compileKotlinIosSimulatorArm64&quot;),<br>        tasks.named(&quot;compileReleaseKotlinAndroid&quot;)<br>    )<br>    doLast {<br>        println(&quot;Finished compilation&quot;)<br>    }<br>}</pre><p>You must be asking yourself what are all these lines of scripting code right?.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F6219070&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fcalculation-math-hangover-allen-zach-galifianakis-gif-6219070&amp;image=https%3A%2F%2Fmedia.tenor.com%2F5vo_w_jDfwgAAAAN%2Fcalculation-math.png&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/da28ac5adb31a44a2c922641b6508b34/href">https://medium.com/media/da28ac5adb31a44a2c922641b6508b34/href</a></iframe><p>Let’s explain it by sections:</p><p>The <strong>kotlin</strong> section contains the:</p><ul><li><strong>targets</strong>: You’ll find the configuration for each target. There’s an important thing on the ios configuration, the exports, these are needed as we need to export the libraries we use on the kotlin code, we left an example with the kotlin standard library there.</li><li><strong>cocoapods</strong>: this block sets the information that will be saved on the podspec. and the framework package configurations. you can add the information to the version catalog and access it as it’s described on the snippet, there’s one important value to keep in mind here as it will be used later on the pod file configuration. The name on the root cocoapods configuration and basename under the framework configuration must be the same and those will configure the name used to get the library on cocoapods.</li><li><strong>sourcesets</strong>: This block configures each source set and their dependencies. You’ll notice a difference between the commonMain and the rest of the sourcesets, the use of api() instead of implementation() , this is due to the export() requirement for ios, you are exposing these dependencies on the sourceset and then embedding them on the final package.</li></ul><p>The <strong>android</strong> section contains the configuration needed for the android library package, we left some empty fields for you as an exercise, you can create your own android.versions.toml file with the required configurations and use them here. we are setting all the possible java compilations to use version 17, this ensures that there’s no conflict on what’s compiled.</p><p>The <strong>publishing</strong> section contains the maven publishing configuration. There are a few important pieces here too:</p><ul><li>url = uri(&quot;https://maven.pkg.github.com/user/repo&quot;) you should replace user and repo with your own user and repo on github.</li><li>System.getenv()[&quot;MYUSER&quot;] this will be used on the publish action, you will have to save MYUSER as an environment variable with your github username</li><li>System.getenv()[&quot;MYPAT&quot;] this will be used on the publish action, you will have to save MYPAT as an environment variable with a <a href="https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-personal-access-token-classic">private access token created on github</a>.</li></ul><p>The rest of the configuration in this section disables the ios publishing on maven as we will publish the ios framework using the repo as any regular cocoapods library.</p><p>The <strong>afterEvaluate</strong> section contains a few configurations that reduce the compilation time (disable the iOS debug compilation tasks) and also sets the language version to 17 on java compilation tasks. finally it sets the test logging to show when it starts and ends each task, this helps on the testing actions.</p><p>The <strong>configurations.forEach</strong> section fixes a bug on some configurations missing an id attribute that appeared after gradle 8.</p><p>We reached the final part of the build script, you can see 3 tasks created:</p><ul><li>moveIosPodToRoot moves the ios framework output to the root of the project, making it accessible when using cocoapods.</li><li>publishPlatforms is the task that triggers the publishing of the android maven package and the ios one too. This task will push a commit with the ios package on the same repo and create a new tag with the version set on the common.versions.toml version catalog.</li></ul><p>Well, this is the end of the gradle scripts configuration.</p><h3>The Test Action</h3><p>Well, the heavy project configuration is done, you pushed the code to your github repo and you can add your code and compile, now, we need to setup the github actions that will run the tests and publish new versions once we push our code. This section is about the tests action.</p><p>You should remember that we had 2 parameters as environment variables:</p><ul><li>System.getenv()[&quot;MYUSER&quot;]</li><li>System.getenv()[&quot;MYPAT&quot;]</li></ul><p>We need to add these environment variables to the actions secrets, you’ll go to https//github.com/USER/REPO/settings/secrets/actions and add them with the name you prefer, remember you will need these names later for the actions scripts.</p><p>Now that you added the secrets we can continue with the action scripts. If you need help on how to create a github actions workflow go to the <a href="https://docs.github.com/en/actions/quickstart">official docs</a>. For simplicity we are leaving the entire script and will explain each step below:</p><pre>name: Run tests<br><br>on:<br>  workflow_dispatch:<br>  pull_request:<br><br>concurrency:<br>  group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}<br>  cancel-in-progress: true<br><br>jobs:<br>  tests:<br>    name: Run tests<br>    runs-on: [macos-12]<br>    timeout-minutes: 90<br>    env:<br>      DEVELOPER_DIR: /Applications/Xcode_14.2.app/Contents/Developer<br><br>    steps:<br>      - name: Checkout<br>        uses: actions/checkout@v1<br><br>      - name: Set up JDK 17<br>        uses: actions/setup-java@v2<br>        with:<br>          java-version: &#39;17&#39;<br>          distribution: &#39;adopt&#39;<br><br>      - name: Setup Gradle<br>        uses: gradle/gradle-build-action@v2<br><br>      - name: Grant execute permission for gradlew<br>        run: chmod +x gradlew<br><br>      - name: Run Android Tests<br>        run:  ./gradlew shared:testReleaseUnitTest<br><br>      - name: Run iOS Tests<br>        run:  ./gradlew shared:iosX64Test<br><br>      - if: github.event_name == &#39;pull_request&#39;<br>        name: Create code coverage<br>        run:  ./gradlew shared:koverXmlReport<br><br>      - if: github.event_name == &#39;pull_request&#39;<br>        name: Add coverage report to PR<br>        id: kover<br>        uses: mi-kas/kover-report@v1<br>        with:<br>          path: ${{ github.workspace }}/shared/build/reports/kover/xml/report.xml<br>          token: ${{ secrets.GITHUB_TOKEN }}<br>          title: Code Coverage<br>          update-comment: true<br>          min-coverage-overall: 80<br>          min-coverage-changed-files: 80<br>          coverage-counter-type: LINE</pre><ul><li>The initial configuration sets this action to be triggered on pull requests, and also to be manually run when needed.</li><li>We set the action to cancel any existing runs if it’s triggered in parallel, this is useful when pushing code to the same PR in short time spans.</li><li>We are setting the action to run on macos 12 as we need this for the ios framework to be compiled.</li><li>we set a timeout of 90 minutes and set the xcode version to be 14.2</li></ul><p>Now let’s check the steps:</p><ol><li>We checkout the code.</li><li>We run the JDK 17 configuration.</li><li>We setup the gradle configuration and caching, this will save us some time after the initial run.</li><li>We grant execute permissions to the gradle executable.</li><li>We run the android tests.</li><li>We run the iOS tests.</li><li>If the action is triggered from a PR we build the code coverage xml report.</li><li>Again, if the action is triggered from a PR, we publish the coverage report to the PR.</li><li>When you see the tests running, you’ll find the result of the tests logging setup we did on the previous post, each test will have a START and PASSED or FAILED log.</li><li>When you see the action running, there will be some extra step for the gradle caching, this is the 3 step saving the cache after the run.</li></ol><h3>The Publish Action</h3><p>This is the final step in the setup, you might have already started to add your code, and you have your first PR, the tests have passed, you updated the version of the library in the common.versions.toml catalog, everything’s ready for the version to be published and consumed from each platform.</p><p>As on the previous section, here’s the script for you to see/use, we’ll explain the steps below so you can understand the process:</p><pre>name: Publish version<br><br>on:<br>  workflow_dispatch:<br>jobs:<br>  testflight:<br>    name: Publish libraries<br>    runs-on: [macos-12]<br>    timeout-minutes: 90<br>    env:<br>      MYUSER: ${{ secrets.MYUSER }}<br>      MYPAT: ${{ secrets.MYPAT }}<br>      DEVELOPER_DIR: /Applications/Xcode_14.2.app/Contents/Developer<br>    if: github.ref == &#39;refs/heads/main&#39;<br>    steps:<br>      - name: Checkout<br>        uses: actions/checkout@v1<br><br>      - name: Set up JDK 17<br>        uses: actions/setup-java@v2<br>        with:<br>          java-version: &#39;17&#39;<br>          distribution: &#39;adopt&#39;<br><br>      - name: Setup Gradle<br>        uses: gradle/gradle-build-action@v2<br><br>      - name: Github credentials<br>        uses: extractions/netrc@v1<br>        with:<br>          machine: github.com<br>          username: ${{ secrets.MYUSER }}<br>          password: ${{ secrets.MYPAT }}<br><br>      - name: Github config<br>        run: |<br>            git config --global user.name &quot;${{ env.MYUSER }}&quot;<br>            git config --global user.email &quot;YOUREMAIL@YOURDOMAIN.COM&quot;<br>            git checkout -b main<br><br>      - name: Grant execute permission for gradlew<br>        run: chmod +x gradlew<br><br>      - name: Publish version<br>        run:  ./gradlew publishPlatforms</pre><ul><li>This workflow will be triggered manually and will <strong>ONLY</strong> run on the main branch, this is done to avoid versions being spread across branches.</li><li>We get the user and private access token that we saved on the previous post, as we will push the result of the ios framework compilation to the repo and have the tag added too on the release process.</li></ul><p>Now the steps:</p><ol><li>The regular checkout.</li><li>We setup the JAVA JDK.</li><li>We setup gradle</li><li>We save the user and pat on the github configuration, since the VM gets wiped once the action is completed we don’t have to worry about deleting this later and nothing is published or left anywhere accessible to the public.</li><li>We add the user and e-mail to the github configuration.</li><li>We give execute permissions to the gradle executable.</li><li>we run the publishPlatforms gradle task that we added to the gradle scripts on the 3rd post of these series.</li></ol><p>Depending on your development flow you might publish a new version every time you merge a PR on main or you might have a development branch where you work on several features at the same time and merge to main once in a while, so, each time you merge to main this github workflow will work as a deploy, compiling the libraries for each platform and publishing them to the respective places.</p><p>Remember to update the library version on the version catalog before merging to main or you will get an error when running the publish version action.</p><p>This is the last step in the process of setting up a private KMP library on github. Next you’ll find one more post that explains how to configure your iOS and Android projects to consume the library.</p><p>Hope this post was useful and well written/explained, if you have any question please leave a comment and we’ll read and answer as we can.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f596afc6e09" width="1" height="1" alt=""><hr><p><a href="https://medium.com/teamsnap-engineering/setting-up-a-kmp-shared-library-5f596afc6e09">Setting up a KMP shared library</a> was originally published in <a href="https://medium.com/teamsnap-engineering">TeamSnap Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RecyclerView + SearchView + TabLayout + ViewModel + Koin]]></title>
            <link>https://medium.com/@ar.demon/recyclerview-searchview-tablayout-viewmodel-koin-f9a07ab637c3?source=rss-949231236245------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9a07ab637c3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[alejandro-moya]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Alejandro Moya]]></dc:creator>
            <pubDate>Tue, 24 Dec 2019 22:02:17 GMT</pubDate>
            <atom:updated>2019-12-24T22:02:17.353Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*byx738qD66bRlnvBthEjGg.png" /></figure><p>It’s been a while my fellow padawans. Well, excuse my Star Wars moment.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o7abB06u9bNzA8lu8%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fstarwars-star-wars-the-force-awakens-bb-8-3o7abB06u9bNzA8lu8&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o7abB06u9bNzA8lu8%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="236" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc927ad7ff332b4a8b2b68cc1a3c2525/href">https://medium.com/media/dc927ad7ff332b4a8b2b68cc1a3c2525/href</a></iframe><p>Let’s start again shall we?, it’s been a while since I found something useful to give to the community that I love. We all take knowledge from different places, but it feels good to give something once in a while.</p><p>This time I have an interesting “mix”, we often find blog posts about the usage of some sdk elements and libraries, but it’s hard to find these mixes that help us speed up our process.</p><p>Using a RecyclerView with a SearchView and a TabLayout, making all work inside a ViewModel and injecting the required components with Koin, this is a beautiful way to make your code look clean and beautiful.</p><h4>Let’s go onto the process:</h4><h4>The layout</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a885658e2b1d9851b4448ee78b70cf4d/href">https://medium.com/media/a885658e2b1d9851b4448ee78b70cf4d/href</a></iframe><p>You will see all the components except for the SearchView. Let’s talk a little about the layout details, the toolbar is an include as you might want to customize its look &amp; feel. The tabs will allow us to sort the elements in an ascending or descending order. And last, we will see the RecyclerView that will show the content, it also has the item layout to allow the preview in the layout editor.</p><h4>The menu</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ceca0a684b63bcc3fc4a5e3ca01078a5/href">https://medium.com/media/ceca0a684b63bcc3fc4a5e3ca01078a5/href</a></iframe><p>Here we have the menu with the SearchView, this one is pretty short as it only contains this component.</p><h4>The Activity</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dde14425476f8d985b89997cbb1ac98/href">https://medium.com/media/1dde14425476f8d985b89997cbb1ac98/href</a></iframe><p>The activity contains the interaction with the UI components, it setups the RecyclerView, the TabLayout and the SearchView, there’s a trick on the last two, when the search is active the tabs are visible, otherwise they become invisible to show the original unmodified list. The ViewModel is injected using Koin’s viewModel() method, as you can see there’s no other property except for the searchView .</p><h4>The ViewModel</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd848ccc545f107e956a9389230e3859/href">https://medium.com/media/cd848ccc545f107e956a9389230e3859/href</a></iframe><p>As we can see the first two parameters are the dataSource and the adapter, these are injected using Koins methods, we also have properties to set the sort order desired and the search text, finally a method to apply the filters and a method to reset the list.</p><h4>The DataSource</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65ab3b2f3adc6b47d25e9eeb511d4955/href">https://medium.com/media/65ab3b2f3adc6b47d25e9eeb511d4955/href</a></iframe><p>I Added this as a way to show what the example datasource would look like, but it can be anything you need.</p><h4>The Adapter</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b78989a6f9587b833c83948f52243c73/href">https://medium.com/media/b78989a6f9587b833c83948f52243c73/href</a></iframe><p>The adapter is pretty simple, no filtering is done here, just presenting the data on screen, if needed, any UI action could be setup on the configure method, the context can be retrieved from the view, that removes the need to pass a context and leak memory.</p><h4>The Injection Module</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e15d00aa50555d826e03da3040c0102/href">https://medium.com/media/7e15d00aa50555d826e03da3040c0102/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9af5d15d40d7fa03201c3cb3540026e0/href">https://medium.com/media/9af5d15d40d7fa03201c3cb3540026e0/href</a></iframe><p>As you can see on the gists, the injected components are setup here and the module is setup on the apps onCreate method.</p><h4>Final words</h4><p>With the previous example you will see that the ViewModel holds the filtering capabilities. The Activity only contains the UI portion of the code. There’s a datasource that is injected and could use the repository pattern, making this an MVVMR example. The adapter being on the ViewModel could be a conflict in MVVM’s strict representation, but this adds more flexibility on the list and the best of all, no context was harmed/leaked in the making.</p><p>Hope this helps you on your everyday work, please leave a comment if it did.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9a07ab637c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Those kotlin handy extensions, Retrofit meet Kotlin and Result — part 2]]></title>
            <link>https://medium.com/@ar.demon/those-kotlin-handy-extensions-retrofit-meet-kotlin-and-result-part-2-d64c48726ffc?source=rss-949231236245------2</link>
            <guid isPermaLink="false">https://medium.com/p/d64c48726ffc</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[retrofit2]]></category>
            <category><![CDATA[alejandro-moya]]></category>
            <dc:creator><![CDATA[Alejandro Moya]]></dc:creator>
            <pubDate>Wed, 09 Oct 2019 00:15:09 GMT</pubDate>
            <atom:updated>2019-10-09T18:43:45.736Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>Those kotlin handy extensions, Retrofit meet Kotlin and Result — part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VIWTRXuNRwPLyq5D-FZfMQ.png" /></figure><p>So, After a while using the extension, seeing that it was really useful to me, hoping it is useful to other devs out there, i needed to do the sync part of it, this part is more like a little extension of the original, an extension of the extension if you like (not really but let’s play with the word).</p><p><a href="https://medium.com/@ar.demon/those-kotlin-handy-extensions-retrofit-meet-kotlin-and-result-6d4b149a8ee2">Those kotlin handy extensions, Retrofit meet Kotlin and Result</a></p><p>Retrofit allows us to make calls asynchronously and synchronously, we always use the async way to avoid blocking the UI thread, but what about making a call on another thread already. We don’t want to create a chain of threads, we will try to keep everything in the same place, for this scenario, if we still want to make a call and receive our precious Result&lt;T&gt; we have this new extension:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15ea9444a1910a5eec8386374a3fa317/href">https://medium.com/media/15ea9444a1910a5eec8386374a3fa317/href</a></iframe><p>Quite simple huh?!.</p><p>Please let me know if you use this or my other extensions, it makes me happy to share these.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d64c48726ffc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin — KTX Fragments, Palette & SQLite]]></title>
            <link>https://medium.com/codelitt/kotlin-ktx-fragments-palette-sqlite-bc6fe34a9976?source=rss-949231236245------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc6fe34a9976</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ktx]]></category>
            <dc:creator><![CDATA[Alejandro Moya]]></dc:creator>
            <pubDate>Wed, 12 Jun 2019 20:41:29 GMT</pubDate>
            <atom:updated>2019-06-13T14:06:56.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGCGWk7J1JJl6_zBr1QGcA.png" /></figure><h3>Kotlin — KTX Fragments, Palette &amp; SQLite</h3><p>To continue with the KTX series, we are going to talk about a couple of libraries and their extensions.</p><h4>Fragments</h4><p>We all know that in Android, fragments are an important part of UI construction. We use them many times to create reusable UI elements and to make the UX more flexible.</p><p>This library gives us some handy extensions that will help us on our every day development time.</p><ul><li>So, how do we add the library to the project?:</li></ul><pre>dependencies {<br>    implementation “androidx.fragment:fragment-ktx:$version&quot;<br>}</pre><p>$version will be the current version of the library.</p><ul><li>Now, let’s get the ViewModel‘s:</li></ul><pre>//The activity ViewModel<br>val viewmodel: TheViewModel by activityViewModels()<br>//The fragment ViewModel<br>val viewmodel: TheViewModel by viewModels()<br>//Create a ViewModel<br>val viewmodel: TheViewModel by <br>                        createViewModelLazy(TheViewModel::class, {getViewModelStore()})</pre><p>🚨Be careful, access the property after onAttach or you’ll get an exception💥</p><p>All of the methods are lazy and allow a custom ViewModelProvider.Factory and in the case of viewModels() you can customize the ViewModelStoreOwner.</p><ul><li>If we need to work with FragmentTransaction we can use these two methods:</li></ul><pre>commit(/* optional allowStateLoss */) { transaction -&gt;<br>    //block to be committed if no exception is triggered<br>}</pre><pre>commitNow(/* optional allowStateLoss */) { transaction -&gt;<br>    //block to be committed if no exception is triggered<br>}</pre><h4>Palette</h4><p>If we want to have a color palette available in our apps, we can use this library, so, let’s add it:</p><pre>dependencies {<br>    implementation “androidx.palette:palette-ktx:$version&quot;<br>}</pre><p>$version will be the current version of the library.</p><p>This library is really small, Palette creates a color palette from the “prominent” colors of a bitmap, this extension allows us to use the Target as a key [] . This means:</p><pre>val palette = Palette.from(bitmap).generate<br>val target = Target.VIBRANT<br>val selectedSwatch = palette[target]</pre><h4>SQLite</h4><p>As with our previous post about Anko and the SQLite extensions, we see that KTX wanted to give us some help to with the native database library present on Android. Here’s the snippet that includes this one:</p><pre>dependencies {<br>    implementation “androidx.palette:palette-ktx:$version&quot;<br>}</pre><p>In this case, they didn’t get much into the extensions, there’s only one extension available and it’s the same as the Anko version of the transaction with the block and auto-commit:</p><pre>db.transaction(exclusive = false /* default is true */) {<br>    //transaction related code<br>}</pre><p>In the next post we are going to check the collections extensions, hope you like me showing all the good things @ KTX 😄.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc6fe34a9976" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codelitt/kotlin-ktx-fragments-palette-sqlite-bc6fe34a9976">Kotlin — KTX Fragments, Palette &amp; SQLite</a> was originally published in <a href="https://medium.com/codelitt">Codelitt</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack and KTX]]></title>
            <link>https://medium.com/codelitt/jetpack-and-ktx-ea97b17d9977?source=rss-949231236245------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea97b17d9977</guid>
            <category><![CDATA[android-ktx]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alejandro Moya]]></dc:creator>
            <pubDate>Tue, 28 May 2019 17:00:03 GMT</pubDate>
            <atom:updated>2019-05-28T17:00:03.363Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGCGWk7J1JJl6_zBr1QGcA.png" /></figure><h3>Kotlin — Jetpack and KTX</h3><p>After a series of posts about Anko, it was natural to move to KTX, on this post i’m going to show you the library from google that has many things similar to Anko and some new stuff.</p><h4>First of all, where does KTX come from?</h4><p>Well, google is revamping the set of libraries for android, the old support libraries meant to reduce the operating system fragmentation was renamed to <a href="https://developer.android.com/jetpack/androidx">androidx</a> and together with some new things including KTX they are now called <a href="https://developer.android.com/jetpack">Jetpack</a>. These tools are meant to help android developers not only avoid the system fragmentation, but also have a set of tools that make android development pleasant, more productive and performant.</p><h4>So, what’s the purpose of KTX specifically?</h4><p>As with Anko, this library contains a set of kotlin functions and extensions to different components that will help us with our daily work. Only the core of KTX contains tools for graphics, animations, content, preferences, text, views and widgets.</p><p>With the introduction properly done, let’s move to the real thing. We need to add the library to the project, this is done by adding these things:</p><pre>// in the project gradle file, the root gradle file just in case, <br>// we need to add the google repository<br>repositories {<br> google()<br>}</pre><pre>// on the module gradle file we need to add the library<br>dependencies {<br> implementation &#39;androidx.core:core-ktx:1.0.0&#39;<br>}</pre><p>Now we can start using the library! 🎉</p><p>In the case of KTX the documentation for all the tools is available as part of the android documentation, this is more straightforward than Anko, you don’t need to go thru the library files and check for the available functions and extensions.</p><p>Let’s start with some easy things from the core library:</p><p>We want to extract the color components:</p><pre>val theColor = Color.RED // this could be a Long or Float too, <br>//here it&#39;s Int</pre><pre>theColor.component1() //alpha<br>theColor.component2() //red<br>theColor.component3() //green<br>theColor.component4() //blue</pre><pre>//an Int value<br>theColor.toColorLong()<br>//a Long value<br>theColor.toColorInt()</pre><p>Kotlin has methods to create arrays, maps and other collections, with KTX you can create a ContentValues object in this way:</p><pre>contentValuesOf(Pair(&quot;a&quot;, 0), Pair(&quot;b&quot;, 1))</pre><p>You can edit preferences using this:</p><pre>//defaultSharedPreferences is from Anko, they work really well together huh?<br>//the commit is optional<br>`Context`.defaultSharedPreferences.edit(commit = true) {  <br>    putString(&quot;key&quot;, value)<br>}</pre><p>You can get a system service in this way:</p><pre>val powman = `Context`.getSystemService&lt;PowerManager&gt;()</pre><p>Some bitmap helpers?:</p><pre>myBitmap.toDrawable(getResources())<br>myBitmap.toAdaptiveIcon()<br>myBitmap.toIcon()<br>//also from a ByteArray<br>myByteArray.toIcon()<br>//And Uri<br>myUri.toIcon()<br>//from Drawable<br>//parameters are optional<br>myDrawable.toBitmap(width, height, config&#39;Bitmap.Config&#39;)<br>//Also here parameters are optional<br>myDrawable.updateBounds(left, top, right, bottom)</pre><p>Work with Animator?:</p><pre>myAnimator.addListener(onEnd = {animator -&gt; Unit},<br>      onStart = {animator -&gt; Unit},<br>      onCancel = {animator -&gt; Unit},<br>      onRepeat = {animator -&gt; Unit})<br>myAnimator.addPauseListener(onResume = {animator -&gt; Unit},<br>       onPause = {animator -&gt; Unit})<br>myAnimator.doOnCancel({animator -&gt; Unit})<br>myAnimator.doOnEnd({animator -&gt; Unit})<br>myAnimator.doOnPause({animator -&gt; Unit})<br>myAnimator.doOnRepeat({animator -&gt; Unit})<br>myAnimator.doOnResume({animator -&gt; Unit})<br>myAnimator.doOnStart({animator -&gt; Unit})</pre><p>Access a Location component?:</p><pre>myLocation.component1()<br>myLocation.component2()</pre><p>Some Uri helpers:</p><pre>myUri.toFile()<br>myFile.toUri()<br>myString.toUri()</pre><p>Create a bundle like you would do with other collections:</p><pre>bundleOf(Pair(&quot;a&quot;, 0), Pair(&quot;b&quot;, 1))<br>persistableBundleOf(Pair(&quot;a&quot;, 0), Pair(&quot;b&quot;, 1))</pre><p>Post at time?</p><pre>val time = //uptime in millis Long<br>myHandler.postAtTime(time) { }</pre><pre>val delay = //delay in millis Long<br>myHandler.postDelayed(delay) { }</pre><pre>//both have an optional token parameter</pre><p>We always need to work with text values, some helpers?</p><pre>val numbers = &quot;1234&quot;<br>if (numbers.isDigitsOnly()) { /*will execute this*/ }</pre><pre>val text = &quot;My text &quot;<br>val count = text.trimmedLength() //will return the lenght without the space</pre><pre>val htmlString = &quot;&lt;b&gt;MyBoldText&lt;/b&gt;&quot;<br>val spanned = htmString.parseAsHtml() //this method contains optional parameters to handle different scenarios<br>val newHtmlString = spanned.toHtml() //Also contains an optional parameter</pre><pre>val locale = Locale()<br>val direction = locale.layoutDirection</pre><p>To build spanned text there’s a variety of extension methods that allow to add text and formatting. You can go <a href="https://developer.android.com/reference/kotlin/androidx/core/text/package-summary">here</a> for details on the extension methods.</p><p>Along with these there are extensions for typed AtomicFile, SparseArray, LruCache, Range, extensions to convert to Half, Pair, Size, all of these are available in <a href="https://developer.android.com/reference/kotlin/androidx/core/util/package-summary">this link</a>.</p><p>On the next post we will see more on KTX as this one just covers the core, as with Anko there are lots of things that can be used from these libraries that will make your development experience in Kotlin really pleasant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea97b17d9977" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codelitt/jetpack-and-ktx-ea97b17d9977">Jetpack and KTX</a> was originally published in <a href="https://medium.com/codelitt">Codelitt</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anko & the SQLite]]></title>
            <link>https://medium.com/codelitt/anko-the-sqlite-1dafe7797449?source=rss-949231236245------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dafe7797449</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Alejandro Moya]]></dc:creator>
            <pubDate>Wed, 22 May 2019 17:39:36 GMT</pubDate>
            <atom:updated>2019-05-22T17:39:36.958Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGCGWk7J1JJl6_zBr1QGcA.png" /></figure><h3>Kotlin — Anko &amp; the SQLite</h3><p>In the previous post we went through a layout DSL from Anko that allows dynamic UI building entirely from code. Today we are going to check some great SQLite extensions that will make accessing a SQLite database look like one of the simplest things in our daily work.<br>I personally prefer <a href="https://realm.io/docs">Realm</a> over SQLite for speed, API and it’s core written in C++, but i know many projects rely on SQLite, and we are covering all the good things in Anko, so let’s be good with it.</p><p>In the regular way, to open a SQLite database we need to subclass SQLiteOpenHelper, in Anko we need to subclass ManagedSQLiteOpenHelper and override some methods:</p><pre>class MyDatabaseOpenHelper(ctx: Context) : ManagedSQLiteOpenHelper(ctx, “MyDatabase”, null, 1) {<br>    companion object {<br>        private var instance: MyDatabaseOpenHelper? = null</pre><pre>        @Synchronized<br>        fun getInstance(ctx: Context): MyDatabaseOpenHelper {<br>            if (instance == null) {<br>                instance =             <br>                   MyDatabaseOpenHelper(ctx.getApplicationContext())<br>            }<br>            return instance!!<br>        }<br>    }</pre><pre>    override fun onCreate(db: SQLiteDatabase) {<br>        // Here you create tables<br>        db.createTable(“User”, true, <br>        “id” to INTEGER + PRIMARY_KEY + UNIQUE,<br>        “name” to TEXT,<br>        “email” to BLOB)<br>    }</pre><pre>    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int,    <br>                                           newVersion: Int) {<br>        // Here you can upgrade tables, as usual<br>        db.dropTable(“User”, true)<br>    }<br>}</pre><pre>// Access property for Context<br>val Context.database: MyDatabaseOpenHelper<br> get() = MyDatabaseOpenHelper.getInstance(getApplicationContext())</pre><p>The access property created makes it easy to use the database:</p><pre>database.use {<br>    //’this’ refers to the SQLiteDatabase instance <br>}</pre><p>This is similar to:</p><pre>val db = database.writableDatabase</pre><p>But this last example requires running the commands and calling close() when finished.</p><p>In the previous snippet you see some details about how to create and drop tables:</p><pre>db.createTable(“User”, true, <br> “id” to INTEGER + PRIMARY_KEY + UNIQUE,<br> “name” to TEXT,<br> “email” to BLOB)</pre><pre>///</pre><pre>db.dropTable(“User”, true)</pre><p>Following we should see how to insert, update and delete:</p><pre>database.use {<br>    insert(“User”,<br>    “id” to 42,<br>    “name” to “John”,<br>    “email” to “<a href="/service/mailto:user@domain.org">user@domain.org</a>”)<br> <br>    update(“User”, “name” to “Alice”)<br>    .where(“id = {userId}”, “userId” to 42)<br>    .exec()<br>    //or<br>    update(“User”, “name” to “Alice”)<br>    .`whereSimple`(“id = ?”, 42)<br>    .exec()</pre><pre>    val numRowsDeleted = delete(“User”, <br>    “id = {userID}”, <br>    “userID” to 42)<br>}</pre><p>We could use a transaction for all these operations:</p><pre>database.use {<br>    transaction {<br>        insert(“User”,<br>        “id” to 42,<br>        “name” to “John”,<br>        “email” to “<a href="/service/mailto:user@domain.org">user@domain.org</a>”)<br> <br>        update(“User”, “name” to “Alice”)<br>        .where(“id = {userId}”, “userId” to 42)<br>        .exec()<br>        //or<br>        update(“User”, “name” to “Alice”)<br>        .`whereSimple`(“id = ?”, 42)<br>        .exec()</pre><pre>        val numRowsDeleted = delete(“User”, <br>        “id = {userID}”, <br>        “userID” to 42)<br>    }<br>}</pre><p>There are also replace() insertOrThrow() replaceOrThrow() methods that can be used accordingly.</p><p>Now we should know how to query data right?:</p><pre>val db = database.readableDatabase</pre><pre>db.select(“User”, “email”).exec {<br> //you receive a Cursor with the email column in the block<br>}</pre><pre>db.select(“User”).`whereSimple`(“id = ?”, 42).exec {<br> //you receive a Cursor with the User columns in the block<br>}</pre><p>There are more options for the query builder, also there’s a parsing helper that maps the cursor to an array or map.</p><p>This was the last post about Anko, i hope you found this helpful and encouraging to use these libraries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dafe7797449" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codelitt/anko-the-sqlite-1dafe7797449">Anko &amp; the SQLite</a> was originally published in <a href="https://medium.com/codelitt">Codelitt</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anko & the layouts]]></title>
            <link>https://medium.com/codelitt/anko-the-layouts-c9ce6aadde2a?source=rss-949231236245------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9ce6aadde2a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Alejandro Moya]]></dc:creator>
            <pubDate>Tue, 14 May 2019 19:46:26 GMT</pubDate>
            <atom:updated>2019-05-15T13:51:20.116Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGCGWk7J1JJl6_zBr1QGcA.png" /></figure><h3>Kotlin — Anko &amp; the layouts</h3><p>In the previous post we found some good tools to help reduce code in Android apps. Now we are going to add a twist, we can remove the XML layouts and create a dynamic UI strictly from code, a real power tool from Anko, as this also makes this process really simple and flexible.</p><p>This part of the library is really flexible, you can replace or include xml layouts, and by include I mean you can keep your existing layouts and include them in the dynamic code.</p><p>A quick example:</p><pre>verticalLayout {<br>    padding = dip(5) //remember the dip method from commons?<br>    val user = editText {<br>        hint = “User name”<br>        textSize = 14f<br>    } <br>    val password = editText {<br>        hint = “Password”<br>        textSize = 14f<br>    }<br>    button(“Login”) {<br>        backgroundColor = Color.BLUE<br>        onClick {<br>            toast(“logged in with user ${user.text}”)<br>        }<br>    }<br>}.lparams {<br>    margin = dip(10)<br>}</pre><p>This code is self explanatory, you create a vertical layout with two EditText and one Button, the button is blue and the text size for both fields is 14f, when the button is clicked it shows a toast with the text supplied. The vertical layout has a padding of 5dp and a margin of 10dp, you can also set different sizes for vertical and horizontal, also the classic individual modifiers.</p><p>On the next post we will go through the sqlite tools available on the library.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9ce6aadde2a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codelitt/anko-the-layouts-c9ce6aadde2a">Anko &amp; the layouts</a> was originally published in <a href="https://medium.com/codelitt">Codelitt</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>