<?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 Shivam Shrivastava on Medium]]></title>
        <description><![CDATA[Stories by Shivam Shrivastava on Medium]]></description>
        <link>https://medium.com/@shivamshrivastavaad?source=rss-dd7c8af50418------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gXC-uNjdZH30neyyy0s4zQ.jpeg</url>
            <title>Stories by Shivam Shrivastava on Medium</title>
            <link>https://medium.com/@shivamshrivastavaad?source=rss-dd7c8af50418------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:23:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shivamshrivastavaad/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[Automating Android Releases: A Complete CI/CD Guide using GitHub Actions & Fastlane]]></title>
            <link>https://medium.com/@shivamshrivastavaad/automating-android-releases-a-complete-ci-cd-guide-using-github-actions-fastlane-9006a1951801?source=rss-dd7c8af50418------2</link>
            <guid isPermaLink="false">https://medium.com/p/9006a1951801</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Shivam Shrivastava]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 17:58:41 GMT</pubDate>
            <atom:updated>2026-04-07T17:58:41.455Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wAjnQEZgJMubZ6K8Sdztwg.png" /></figure><p>Deploying an Android app manually can take 20–30 minutes of your time. If you do this weekly, you’re losing hours. In this guide, I will show you how to set up a professional-grade CI/CD pipeline that handles auto-versioning, staged rollouts, and secure secret management.</p><blockquote><strong>Prerequisites<br></strong>• An Android project hosted on GitHub.<br>• An app already live on the Google Play Console.<br>• A Release Keystore (.jks file).</blockquote><blockquote><strong>Step 1: Create a Google Service Account ( </strong><a href="https://console.cloud.google.com/"><strong>Link</strong></a><strong> )</strong></blockquote><p>To allow GitHub to talk to Google Play, you need a “Robot User.”<br>1.Go to Google Cloud Console &gt; IAM &amp; Admin &gt; Service Accounts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hNv-2YZWb61XGIHwRHBcCQ.png" /></figure><p>2.Create a Service Account (e.g., github-actions-deploy).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uzYz42kaPpali8UyylQAZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zqdoZ_GMTu9ndeDSpIpVyA.png" /></figure><p>Select Role: Service Accounts -&gt; Service Account User</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BhRLsD95K9JOtoFoh4cH9g.png" /></figure><p>3.Role: Set to Service Account User.</p><p><strong>After creating the service account, you will see a new email like this:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqSLvz6eaUWdMeCAFDSbqw.png" /></figure><p><strong>Then click on it.</strong></p><p>4. Keys: Go to the “Keys” tab, click Add Key &gt; Create New Key &gt; JSON.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pBUf9_I-lALsJpOW7IYTcg.png" /></figure><p>5.Enable API: Visit this <a href="https://console.cloud.google.com/apis/library/androidpublisher.googleapis.com">link</a> to enable the Google Play Android Developer API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ems_elSzYFEhz6DX3fHYag.png" /></figure><p>6.Link to Play Console: Go to Users and Permissions in the Play Console ( <a href="https://play.google.com/console">Link</a> ), invite the service account email, and grant it Admin (all permissions).</p><figure><img alt="Add Newly created email" src="https://cdn-images-1.medium.com/max/1024/1*isjZiukfLyn0jxqR3sC8-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qtcK8gIqSpBWusWXD9eZzA.png" /></figure><blockquote><strong>Step 2: Prepare Your Secrets (The Base64)</strong></blockquote><p>GitHub Actions runs on a fresh virtual machine, which means it doesn’t have your .jks file or your Service Account JSON. Since these are sensitive, we convert them to Base64 strings to store them as GitHub Secrets.</p><ol><li>Encode your Keystore (.jks)<br>• macOS: base64 -i your_key.jks | pbcopy<br>• Windows: [Convert]::ToBase64String([IO.File]::ReadAllBytes(“your_key.jks”)) | clip</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*kT8l4QMr-xiyPhgCdlTUcA.png" /></figure><blockquote><strong>Note: </strong><em>Open the terminal in the folder where your JKS file is located, and run this command. Make sure you replace the .jks file name with your actual file name. <br></em><strong>After running this command, the Base64 content will be automatically copied to your clipboard.</strong></blockquote><p>2. Encode your Service Account JSON<br>• macOS: base64 -i service_account.json | pbcopy<br>• Windows: [Convert]::ToBase64String([IO.File]::ReadAllBytes(“service_account.json”)) | clip</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*C28pheKvuF5h9fwTpKmPrw.png" /></figure><blockquote><strong>Note: </strong><em>Open the terminal in the folder where your JSON file is located, and run this command. Make sure you replace the .json file name with your actual file name.</em></blockquote><p>3. Add to GitHub Secrets<br>Go to Settings &gt; Secrets and variables &gt; Actions in your repo and add:<br>• RELEASE_KEYSTORE_BASE64: (The string from Step 2.1)<br>• PLAY_CONFIG_JSON: (The string from Step 2.2)<br>• KEYSTORE_PASSWORD, KEY_ALIAS, KEY_PASSWORD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5VobjnCjeX0EZV_2qnSy9Q.png" /><figcaption>Github</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TX-MmeIIIn-2vY8pjOvAHA.png" /></figure><blockquote><strong>Note:</strong> <em>In the Name field, keep the name mentioned above. In the Secret field, paste the Base64-encoded content of the .jks file (RELEASE_KEYSTORE_BASE64) and the .json file (PLAY_CONFIG_JSON). For KEYSTORE_PASSWORD, KEY_ALIAS, and KEY_PASSWORD, there is no need to convert them to Base64 — just paste their original values.</em></blockquote><blockquote><strong>Step 3: Configure Gradle for Auto-Versioning</strong></blockquote><p>We want Fastlane to tell Gradle what the version should be based on the latest build on the Play Store.<br>In your <strong>app-level </strong>build.gradle, add this function at the top:</p><pre>def getMyVersionCode() {<br>    return project.hasProperty(&#39;versionCodeOverride&#39;) ? project.property(&#39;versionCodeOverride&#39;).toInteger() : 1<br>}<br><br>android {<br>    defaultConfig {<br>        versionCode getMyVersionCode()<br>        // ...<br>    }<br>    <br>    signingConfigs {<br>        release {<br>            storeFile = file(&quot;${project.rootDir}/app/release.jks&quot;)<br>            storePassword = System.getenv(&quot;KEYSTORE_PASSWORD&quot;)<br>            keyAlias = System.getenv(&quot;KEY_ALIAS&quot;)<br>            keyPassword = System.getenv(&quot;KEY_PASSWORD&quot;)<br>        }<br>    }<br>}<br><br>signingConfig = signingConfigs.getByName(&quot;release&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-kN1uzo88LUo6F_tWgngrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jgBZ5Xb9Z6HbXtHSD_PIoQ.png" /></figure><blockquote><strong>Step 4: The Fastlane Engine</strong></blockquote><p>Create a folder named fastlane in your project root.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RnJvNwn5Q0FJDAAMStELRw.png" /></figure><p><strong>fastlane/Appfile</strong></p><pre>json_key_file(&quot;service_account_key.json&quot;)<br>package_name(&quot;com.your.package.name&quot;)</pre><p><strong>fastlane/Fastfile<br></strong>This script fetches the latest version code from the Play Store and increments it by 1.</p><pre>default_platform(:android)<br><br>platform :android do<br>  desc &quot;Deploy a new version to the Google Play Store&quot;<br>  # &#39;options&#39; allows us to receive the rollout percentage from GitHub<br>  lane :deploy do |options|<br><br>    # 1. Get current version safely<br>    begin<br>      current_version = google_play_track_version_codes(track: &#39;production&#39;)[0] || 0<br>    rescue<br>      current_version = 0<br>    end<br><br>    new_version_code = current_version + 1<br><br>    # Use the rollout value from GitHub, or default to 0.1 (10%)<br>    rollout_val = options[:rollout] || &quot;0.1&quot;<br><br>    # If rollout is 1.0 (100%), set status to &#39;completed&#39;, otherwise &#39;inProgress&#39;<br>    status = rollout_val == &quot;1.0&quot; ? &quot;completed&quot; : &quot;inProgress&quot;<br><br>    puts &quot;Targeting Rollout: #{rollout_val} with status: #{status}&quot;<br><br>    # 2. Build<br>    gradle(<br>      task: &quot;bundle&quot;,<br>      build_type: &quot;Release&quot;,<br>      flavor: &quot;Prod&quot;,<br>      properties: {<br>        &quot;versionCodeOverride&quot; =&gt; new_version_code<br>      }<br>    )<br><br>    # 3. Upload<br>    upload_to_play_store(<br>      track: &#39;production&#39;,<br>      release_status: status,<br>      rollout: rollout_val,<br>      skip_upload_metadata: true,<br>      skip_upload_images: true<br>    )<br>  end<br>end</pre><blockquote><strong>Step 5: The GitHub Workflow (.yml)<br></strong>Create .github/workflows/deploy.yml. This script orchestrates everything.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TAlFfQqvZTO40CqqIiT74Q.png" /></figure><pre>name: Deploy to Play Store<br><br>on:<br>  push:<br>    branches: [ &quot;liveBranch&quot; ]<br>  workflow_dispatch: # Allows you to run this manually from the Actions tab<br>    inputs:<br>      rollout_percent:<br>        description: &#39;Rollout percentage (e.g., 0.1 for 10%)&#39;<br>        required: true<br>        default: &#39;0.1&#39;<br><br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - name: set up JDK 17<br>        uses: actions/setup-java@v4<br>        with:<br>          java-version: &#39;17&#39;<br>          distribution: &#39;temurin&#39;<br>          cache: gradle<br><br>      - name: Decode Secrets<br>        run: |<br>          echo &quot;${{ secrets.RELEASE_KEYSTORE_BASE64 }}&quot; | base64 --decode &gt; app/release.jks<br>          echo &quot;${{ secrets.PLAY_CONFIG_JSON }}&quot; | base64 --decode &gt; service_account_key.json<br><br>      # --- THIS IS THE IMPORTANT CHANGE ---<br>      - name: Setup Ruby<br>        uses: ruby/setup-ruby@v1<br>        with:<br>          ruby-version: &#39;3.3&#39;<br>          bundler-cache: true<br><br>      - name: Execute Fastlane<br>        run: bundle exec fastlane deploy rollout:${{ github.event.inputs.rollout_percent || &#39;0.1&#39; }}<br>        env:<br>          KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}<br>          KEY_ALIAS: ${{ secrets.KEY_ALIAS }}<br>          KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}</pre><blockquote><strong>Step 6: How to Run the Pipeline</strong></blockquote><p>Once you push this setup to your liveBranch, you have two ways to deploy:<br>1. Automatic: Simply push code to liveBranch. The pipeline will trigger and release your app to 10% of users by default.<br>2. Manual (Custom Rollout): Go to the Actions tab in your GitHub repository, select “Deploy to Play Store,” and click Run workflow. Here, you can type in 0.05 for 5% or 1.0 for a full 100% release.</p><blockquote><strong>After pushing the code, go to GitHub and open the Actions tab.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hqW5gbiJeDIqK9aqdtLyWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yg38kPSahpLmpd0vFOfgAA.png" /></figure><p><strong><em>=&gt; “Quote: ‘Learn something new every day.😊’ Keep coding!😍”</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9006a1951801" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Private Android SDK with Clean Architecture and GitLab]]></title>
            <link>https://medium.com/@shivamshrivastavaad/building-a-private-android-sdk-with-clean-architecture-and-gitlab-538c7c34eb09?source=rss-dd7c8af50418------2</link>
            <guid isPermaLink="false">https://medium.com/p/538c7c34eb09</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[sdk]]></category>
            <dc:creator><![CDATA[Shivam Shrivastava]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 19:54:46 GMT</pubDate>
            <atom:updated>2024-12-20T05:01:54.870Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nC7KMUE2Plt4HxTAiidoiQ.png" /></figure><p><strong>In this article, we will cover all the key points in detail.</strong></p><p>I will explain the following concepts step by step:</p><p>• <strong>What is an SDK?</strong></p><p>• <strong>Why do we need an SDK?</strong></p><p>• <strong>Why do we need a Private SDK?</strong></p><p>Additionally, we will provide a <strong>complete setup guide</strong> and explain every concept with clear details and examples.</p><p><strong>1) What is an SDK?</strong></p><p>=&gt; An <strong>SDK (Software Development Kit)</strong> is a collection of tools, libraries and code samples that developers use to create software for a specific platform, device, or service.</p><p><strong>2) Why do we need an SDK?</strong></p><p>=&gt; I will explain with a scenario so that you can relate to and understand it better.</p><p><strong>Scenario:</strong></p><p>You have a functionality in your app that you want to share with your client. However, the client doesn’t want to use your app because they already have their own app. Instead of using your entire app, they want to integrate just that specific functionality from your app into their own.</p><p><strong>Explanation:</strong></p><p>In this case, the SDK becomes essential. With the right SDK, you can create a package or library containing that specific functionality. Your client can then integrate this functionality into their own app without needing to use your entire app. This allows you to share just the feature, saving both time and effort for the client, and it avoids unnecessary dependencies.</p><p>Without the SDK, replicating this functionality manually in the client’s app would be complex, time-consuming, and inefficient. The SDK provides a clean and easy way to share specific parts of your app’s functionality with others.</p><p><strong>3) Why do we need a Private SDK?<br></strong>A private SDK is needed when you want to share specific functionalities, tools, or services with a limited set of users or clients, without exposing them to the public. It allows you to:</p><p>1. Secure proprietary features by restricting access to trusted clients or partners.</p><p>2. Keep your code safe and secure, ensuring that others cannot misuse your SDK or steal your code.</p><blockquote>Let’s jump into the coding and setup part.</blockquote><p>=&gt; “First, we need to create a project and a repository on GitLab with a private repository. Then, add the project to GitLab.”<br>=&gt; After adding the project to GitLab, go to Android Studio and open the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVsQDUuzU0wuIynD4bjQmw.png" /></figure><p>Go the File-&gt; New -&gt; <strong>New Module </strong>and <strong>click on it</strong>.</p><p>After clicking this, the screen will appear. In it, select Android Library tab. Change the Module Name and package name according to your preference and click on finish button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*adF8mGwEJeA3naQvZSC5AQ.png" /></figure><p>=&gt; After clicking the <strong>Finish</strong> <strong>button</strong>, your project will sync again. Once the sync is complete, your project should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*f1WiCJVZw61iiujkkxX_3w.png" /></figure><blockquote>Here, you can see a new module has been added with the name ‘mylibrary’. I haven’t changed the name, so it shows ‘mylibrary’. Otherwise, it will show your module name.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*IL17D1340J_fHP7_8RTA_A.png" /></figure><p>Here, you can see that the ‘mylibrary’ module has a manifest file and a module directory where you can write your code. You can also add all necessary files in the module directory, such as res, drawable, layout, and values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*Y9cXay6PntTVw2BvLKuWtw.png" /><figcaption>Like This</figcaption></figure><p>=&gt; In my module, you can see I have added all the necessary folders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*6ypae4h3wsrsWn55-r4UEA.png" /></figure><blockquote>Note: If you are using any third-party library in your module, you must add the dependency in the module’s (build.gradle.kts) file. After adding all dependencies and configurations, you need to build the project.</blockquote><p>=&gt; Go the <strong>Build-&gt; Click on Make project.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*jRrrsi-U8HNMo8iAqYMvdw.png" /></figure><p>=&gt; After Making project you can see the aar file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*zigMEtArdZ1n21W-Pf60Dg.png" /></figure><p>=&gt; <strong>AAR</strong> : In Android, an <strong>AAR (Android Archive)</strong> is a file format that contains all the necessary components for an Android library. It’s similar to a ZIP file, but specifically for Android apps and libraries.</p><p>Think of an AAR like a ready-to-use “package” or “bundle” of code and resources (like images, layouts, etc.). When you create a library in Android, you can package it into an AAR file and share it with other developers.</p><p>=&gt; Once you’re done up to this point, you need to set up your Gradle for publishing your library on Maven.</p><blockquote><strong>Maven</strong> is a tool used to manage and build projects, mainly in Java. It’s like a helper that automates processes like downloading libraries, compiling code, and packaging everything together. Think of Maven as a toolkit that helps developers organize and share their code more easily.</blockquote><h4><strong>How does Maven play a role in publishing an SDK or library?</strong></h4><p>When you create an SDK or library (a set of reusable code), you might want to share it with others or use it in different projects. Maven helps you do this by allowing you to publish your library to a <strong>Maven Repository</strong> (a place where libraries are stored and shared). Once your library is published on Maven, other developers can easily use it in their projects by simply adding a line of code that tells Maven to download it.</p><p>=&gt; Go to the module’s (build.gradle.kts) file and add these lines.</p><pre>plugins {<br>    alias(libs.plugins.android.library)<br>    alias(libs.plugins.kotlin.android)<br>    alias(libs.plugins.ksp)<br>    id(&quot;maven-publish&quot;) // Add this<br>}</pre><pre>publishing {<br>    publications {<br>        create&lt;MavenPublication&gt;(&quot;release&quot;) {<br>            groupId = &quot;com.swapping&quot;<br>            artifactId = &quot;Swapping&quot;<br>            version = &quot;1.0.0&quot;<br>            // Publish the AAR file explicitly<br>            artifact(&quot;${layout.buildDirectory.get()}/outputs/aar/mylibrary-release.aar&quot;) {}<br>            <br>            pom.withXml {<br>                val dependencies = asNode().appendNode(&quot;dependencies&quot;)<br>                configurations.getByName(&quot;releaseCompileClasspath&quot;).resolvedConfiguration.firstLevelModuleDependencies.forEach {<br>                    val dependency = dependencies.appendNode(&quot;dependency&quot;)<br>                    dependency.appendNode(&quot;groupId&quot;, it.moduleGroup)<br>                    dependency.appendNode(&quot;artifactId&quot;, it.moduleName)<br>                    dependency.appendNode(&quot;version&quot;, it.moduleVersion)<br>                }<br>            }<br>        }<br>    }<br>    repositories {<br>        maven {<br>            url = uri(&quot;https://gitlab.com/api/v4/projects/projectId/packages/maven&quot;) // Replace projectId with your real project id example:123456<br>            name = &quot;GitLab&quot;<br>            credentials(HttpHeaderCredentials::class) {<br>                name = &quot;Private-Token&quot;<br>                value = &quot;Pass Here Gitlab Access token&quot; // Here pass gitlab access token <br>            }<br>            authentication {<br>                create&lt;HttpHeaderAuthentication&gt;(&quot;header&quot;)<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9qcLDvkSYF9U-CIMyJJFw.png" /><figcaption>Here, you have to “publishing” it.</figcaption></figure><p>Above, you can notice I declared <strong>groupId</strong>, <strong>artifactId</strong>, <strong>version</strong>, and <strong>pom</strong>.</p><p><strong>1. groupId = “com.swapping”:</strong></p><p>• The groupId is like a namespace or a unique identifier for your library. It helps to avoid conflicts with other libraries. Typically, it’s based on the domain name you own (for example, com.example or com.swapping).</p><p>• It’s used to group related libraries together, often representing the organization or project that owns the library.</p><p><strong>2. artifactId = “Swapping”:</strong></p><p>• The artifactId is the name of your library or SDK. It’s what other developers will use to reference your library when they add it to their project.</p><p>• In this case, the library is called “Swapping”. It uniquely identifies the specific library within the group.</p><p><strong>3. version = “1.0.0”:</strong></p><p>• The version specifies the version of your library. This helps developers know if they’re using the latest version or a specific older version.</p><ul><li>Versioning follows a common format like major.minor.patch (e.g., 1.0.0). When you make updates or fixes to the library, you change the version number accordingly.</li></ul><p><strong>4. pom.withXml: </strong>This block customizes the <strong>POM (Project Object Model)</strong> file that will accompany the library in the Maven repository. The POM file contains metadata about the library, including its dependencies.</p><ul><li>appendNode(“dependencies”): This adds a &lt;dependencies&gt; section to the POM.</li><li>configurations.getByName(“releaseCompileClasspath”).resolvedConfiguration.firstLevelModuleDependencies.forEach {…}: This part goes through the dependencies defined for your project and adds them to the &lt;dependencies&gt; section in the POM. It pulls the groupId, artifactId, and version of each dependency and adds it as a &lt;dependency&gt; node in the XML.</li></ul><blockquote><strong>Generate gitlab token:-<br></strong>Log in to GitLab -&gt; Click on the avatar image -&gt; Then click on your name or user ID.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*DW3u8IpfwvFncxYs0Rp_xQ.png" /></figure><blockquote>Then, the profile screen will appear. Click on the edit option.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92mwkHbBydMf6T1BtEViZQ.png" /></figure><blockquote>Then, on the left-hand side, you can see the ‘Access Tokens’ option. Click on it and generate an access token by clicking the ‘Add New Token’ option.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2JfYBj6_1gW1r2QmrWJvDw.png" /></figure><blockquote><strong>Find projectID</strong></blockquote><p>Click on the ‘Projects’ option and select your project. Then, go to <strong>Project Settings</strong> -&gt; <strong>General</strong>. In this section, you will find the Project ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFfilWWRk7saSVgRAkmt4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LXdqEBXkb0HSv5n1G2V0cQ.png" /></figure><p>Now that everything is done, you just have to run a few commands, and your library will be published on Maven.</p><p>Run the command in the Android Studio terminal:<br>1) ./gradlew clean</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FfLWEVqLl5mzzkmOaMm25g.png" /></figure><p>2) ./gradlew build</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6KkPn9TnMfJkqX9RKMbBWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VoSVL3bVGsb8_LCSUdfJcg.png" /></figure><p>3) ./gradlew publish</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*ArFG-N4BRqFoF2nJz7YthQ.png" /></figure><p>Now you can check your gitlab account library will publish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qO6c23wDV62gD84P2T9A0w.png" /></figure><blockquote><strong>Note: These two commands are mandatory whenever you increase the release version or publish the library: ./gradlew build and ./gradlew publish.</strong></blockquote><h3>How to use this library in another project.</h3><blockquote>Open the other project, then open the <strong>build.gradle</strong> file, add the library and GitLab credentials, and sync the project.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JknHtQLNUt57-Cr_rpdTMw.png" /></figure><blockquote>And one last step: add this line in <strong>settings.gradle.kts</strong></blockquote><pre>      maven {<br>            url = uri(&quot;https://gitlab.com/api/v4/projects/65349773/packages/maven&quot;)<br>            name = &quot;GitLab&quot;<br>            credentials(HttpHeaderCredentials::class) {<br>                name = &quot;Private-Token&quot;<br>                value = &quot;glpat-MreizyeeC2xzXbMBzJqZ&quot;<br>            }<br>            authentication {<br>                create&lt;HttpHeaderAuthentication&gt;(&quot;header&quot;)<br>            }<br>        }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jnKnMgmmp9_q7l6jNqyvdg.png" /></figure><p>After the sync is complete, you will be able to access the SDK.</p><blockquote><strong>If you find this useful, please hitting the like button and leaving a comment. Your feedback is incredibly valuable to me!</strong></blockquote><p>“Quote: ‘Learn something new every day.😊’ Keep coding!😍”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=538c7c34eb09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practices for Securing Your Mobile App with NDK]]></title>
            <link>https://medium.com/@shivamshrivastavaad/best-practices-for-securing-your-mobile-app-with-ndk-e8191e46a416?source=rss-dd7c8af50418------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8191e46a416</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[android-ndk]]></category>
            <dc:creator><![CDATA[Shivam Shrivastava]]></dc:creator>
            <pubDate>Thu, 22 Aug 2024 17:57:55 GMT</pubDate>
            <atom:updated>2024-08-22T17:57:55.555Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M-SbnNxcbcJuUb3WUIohVg.png" /></figure><p>Hello, learners! Today, we’ll explore how to secure your app using NDK. But first, let’s understand why it’s important to secure your app.</p><p>In our apps, we often use sensitive information like Google Map keys or other API keys. If these fall into the wrong hands, they can be misused. Similarly, when you send login credentials to the backend during the login process, anyone could easily inspect and steal this information through <strong>reverse engineering</strong>.</p><p>So today, we’ll learn how to protect your app from these risks and keep your data safe.</p><blockquote><strong>What is NDK?</strong></blockquote><p>=&gt; The <strong>NDK</strong> (Native Development Kit) is a toolset provided by Android that allows developers to write portions of their app using native code languages like <strong>C</strong> and <strong>C++</strong>. NDK can be used to protect sensitive parts of your app’s code by moving it to native code, which is harder to reverse-engineer compared to Java or Kotlin code.</p><p><strong>=&gt;</strong> <strong>Let’s do some practical work.</strong></p><p><strong>Step 1: </strong>Install <strong>NDK</strong> and <strong>CMake</strong> SDK (From SDK Tools)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6vkHDdT3BBoZr-vdI0bn9g.png" /></figure><p><strong>Step 2:</strong> Click on the main directory and create a new directory named ‘jni’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*BF-A0bi_WiG84qiBEi9dsA.png" /></figure><p><strong>Step 3: </strong>Create an Android.mk file in the jni folder and paste the following code into it.</p><blockquote>This file is used by the NDK build system to specify the source files and build settings for your native code. It defines how to compile and link your C/C++ code into shared libraries.</blockquote><pre>LOCAL_PATH := $(call my-dir)<br><br>include $(CLEAR_VARS)<br><br>LOCAL_MODULE := keys<br>LOCAL_SRC_FILES := keys.c<br><br><br>include $(BUILD_SHARED_LIBRARY)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XLVqhVqqcAi161_j-us-IA.png" /></figure><p><strong>Step 4:</strong> In the same directory, create an Application.mk file and add the following code to it.</p><blockquote>This file provides global build settings for your project, such as specifying the platform version and enabling or disabling certain features. It helps configure how the NDK compiles and links your code.</blockquote><pre>APP_ABI := all</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T8zDyyBX7brg1Z5zCiSB2A.png" /></figure><p><strong>Step 5: </strong>Create a file named keys.c and paste the following code into it.</p><blockquote>This file typically contains sensitive data or configurations used by your native code. It’s where you might store and manage keys, credentials, or other critical data needed by your app’s native components.</blockquote><pre>#include &lt;jni.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;android/log.h&gt;<br><br><br>JNIEXPORT jstring JNICALL<br>Java_com_myapplication_MainActivity_getApiKey(JNIEnv *env, jobject instance) {<br>    return (*env)-&gt; NewStringUTF(env, &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mkEy0f2EqHWY4_TyVvmWJQ.png" /></figure><p><strong>Note:</strong> Instead of “ABCDEFGHIJKLMNOPQRSTUVWXYZ”, please use your own API key.</p><p><strong>Note:</strong> One important point to note here is that in the C file, we replace periods (.) with underscores (_) and need to define the complete path. This means specifying the exact location where this function will be used in your project. <strong>Example:</strong> Java.com.myapplication.MainActivity.getApiKey <strong>-&gt;</strong> Java_com_myapplication_MainActivity_getApiKey</p><p><strong>Step 6:</strong> Go to buld.gradle(Module:app) and Add NDK Version and C file path</p><pre> ndkVersion = &quot;27.0.11902837&quot; // NDK Version<br><br>    externalNativeBuild {<br>        ndkBuild {<br>            path = File(&quot;src/main/jni/Android.mk&quot;) //path of Android.mk file<br>        }<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ctg5ZRQczmoM6Geq36-otQ.png" /></figure><p><strong>Note:</strong> To find the NDK version, navigate to the Android SDK location.( For <strong>mac</strong> -&gt; /Users/{username}/Library/Android/sdk/ndk)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hadZRk3BjrAyL9gfb8KGfg.png" /></figure><p><strong>Step 7: </strong>Now that everything is set up, it’s time to use it in your file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sp1sowMs6rB6dM0iVb7oqw.png" /></figure><pre>    init {<br>        System.loadLibrary(&quot;keys&quot;)<br>    }<br><br>    private external fun getApiKey(): String</pre><blockquote>Use System.loadLibrary(&quot;keys&quot;) to load your C file into the Android app. Afterward, you can call the public native method String getApiKey(), which returns an API key as a string that you can use as needed.&quot;</blockquote><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ri1dHzaBU-oZj1-9K_WSbw.png" /></figure><p>=&gt; Github link : <a href="https://github.com/Dev-ShivamShrivastava/SecureApp">https://github.com/Dev-ShivamShrivastava/SecureApp</a></p><p>=&gt; “Quote: ‘Learn something new every day.😊’ Keep coding!😍”</p><blockquote><strong><em>If you find this useful, please hitting the like button and leaving a comment. Your feedback is incredibly valuable to me!</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8191e46a416" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server Driven UI in Flutter.]]></title>
            <link>https://medium.com/@shivamshrivastavaad/server-driven-ui-in-flutter-6affa756b68c?source=rss-dd7c8af50418------2</link>
            <guid isPermaLink="false">https://medium.com/p/6affa756b68c</guid>
            <category><![CDATA[riverpod]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Shivam Shrivastava]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 19:51:39 GMT</pubDate>
            <atom:updated>2024-07-22T19:51:39.419Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNYb2oZ628Vk6S6kar9sbw.png" /></figure><p>Hello <strong>Learner</strong>, today we are going to learn something interesting. Often, you might have noticed that during a festival or an occasion, the home screen or some other screen of an app completely changes. <strong>How does that happen?</strong> Today, we will learn about it. How does the UI of the screen change without updating the app? So, <strong>let’s get started.</strong></p><blockquote><strong>What is Server Driven UI?</strong></blockquote><p>=&gt; In a traditional mobile app, the UI is usually hard-coded into the app itself. If developers want to change how the app looks or behaves, they need to release a new version of the app, which users then have to download and install. With server-driven UI, the server sends instructions to the app on how to display its interface, which means the UI can be updated dynamically, instantly, and without needing a full app update.</p><blockquote><strong>=&gt; Benefit of Server Driven UI</strong></blockquote><ol><li><strong>Dynamic Updates: </strong>Allows instant UI changes without requiring app updates from the app store.</li><li><strong>Centralized Control: </strong>Centralized management of UI ensures consistent experience across all users.</li><li><strong>Flexibility:</strong> Easily adapt UI for different events, promotions.</li></ol><blockquote><strong>=&gt; Limitations of Server Driven UI</strong></blockquote><ol><li><strong>Debugging Complexity:</strong> Harder to debug due to server-controlled UI; errors are difficult to trace.</li><li><strong>Limited Customization: </strong>Difficult to adapt UI based on user preferences or device capabilities.</li><li><strong>Performance Concerns: </strong>Frequent network requests for UI data can slow down app performance.</li></ol><p><strong>=&gt;</strong> <strong>Let’s do some practical work.</strong></p><blockquote>Basically, we receive the type of view from the server. Based on this type, we create the view at runtime and add it to the screen. There is common code for each view type, which we call based on the type. This function creates and returns the view of that type.</blockquote><p><strong>Let’s suppose</strong> we receive a response of this type from the server:-</p><pre>[<br>        {<br>            &quot;type&quot;: &quot;image&quot;,<br>            &quot;text&quot;: &quot;Image Description&quot;,<br>            &quot;color&quot;: &quot;0xff00ff00&quot;<br>        },<br>        {<br>            &quot;type&quot;: &quot;space&quot;,<br>            &quot;text&quot;: &quot;&quot;,<br>            &quot;color&quot;: &quot;&quot;<br>        },<br>        {<br>            &quot;type&quot;: &quot;sizebox&quot;,<br>            &quot;text&quot;: &quot;&quot;,<br>            &quot;color&quot;: &quot;&quot;<br>        },<br>        {<br>            &quot;type&quot;: &quot;text&quot;,<br>            &quot;text&quot;: &quot;Welcome to Morning star Travels!&quot;,<br>            &quot;color&quot;: &quot;0xff0000ff&quot;<br>        },<br>        {<br>            &quot;type&quot;: &quot;sizebox&quot;,<br>            &quot;text&quot;: &quot;&quot;,<br>            &quot;color&quot;: &quot;&quot;<br>        },<br>        {<br>            &quot;type&quot;: &quot;textfield&quot;,<br>            &quot;text&quot;: &quot;Enter source location&quot;,<br>            &quot;color&quot;: &quot;0xff0000ff&quot;<br>        },<br>        {<br>            &quot;type&quot;: &quot;sizebox&quot;,<br>            &quot;text&quot;: &quot;&quot;,<br>            &quot;color&quot;: &quot;0xff00ff00&quot;<br>        },<br>        {<br>            &quot;type&quot;: &quot;textfield&quot;,<br>            &quot;text&quot;: &quot;Enter destination location&quot;,<br>            &quot;color&quot;: &quot;0xff0000ff&quot;<br>        },<br>        <br>        {<br>            &quot;type&quot;: &quot;button&quot;,<br>            &quot;text&quot;: &quot;Search&quot;,<br>            &quot;color&quot;: &quot;0xFFFFFF&quot;<br>        },<br>        {<br>            &quot;type&quot;: &quot;stack&quot;,<br>            &quot;text&quot;: &quot;&quot;,<br>            &quot;color&quot;: &quot;0xFFFFFF&quot;<br>        },<br>    ];</pre><blockquote>In this Flutter project, I have used Riverpod for state management.</blockquote><blockquote><strong>Let’s see how to manage this in Flutter.</strong></blockquote><p><strong>Step 1: Create a Model Class</strong><br>First, we’ll create a model class to represent the data structure of the server response. This will help us parse the JSON data we receive from the server.</p><pre>class WidgetConfig {<br>  final String type;<br>  final String? text;<br>  final String? color;<br><br>  WidgetConfig({required this.type, this.text, this.color});<br><br>  factory WidgetConfig.fromJson(Map&lt;String, dynamic&gt; json) {<br>    return WidgetConfig(<br>      type: json[&#39;type&#39;],<br>      text: json[&#39;text&#39;],<br>      color: json[&#39;color&#39;],<br>    );<br>  }<br>}</pre><p><strong>Step 2: Make a Network Request<br></strong>Once you have the model class, you can make a network request to fetch the data from the server. Here’s how you can do it in Flutter:</p><pre><br>Future&lt;List&lt;WidgetConfig&gt;&gt; fetchWidgetConfig() async {<br>  final response = await http.get(Uri.parse(&#39;http://192.168.1.***:4000/dynamic_ui&#39;)); // Enter your server url<br><br>  if (response.statusCode == 200) {<br>    List&lt;dynamic&gt; jsonData = json.decode(response.body);<br>    return jsonData.map((json) =&gt; WidgetConfig.fromJson(json)).toList();<br>  } else {<br>    throw Exception(&#39;Failed to load widget config&#39;);<br>  }<br>}</pre><p><strong>Step 3: Parse the Response and Render the UI<br></strong>To parse the server response and render the UI dynamically and also Manage Network state</p><pre> FutureBuilder&lt;List&lt;WidgetConfig&gt;&gt;(<br>        future: fetchWidgetConfig(),<br>        builder: (context, snapshot) {<br>          if (snapshot.connectionState == ConnectionState.waiting) {<br>            return Center(child: CircularProgressIndicator());<br>          } else if (snapshot.hasError) {<br>            return Center(child: Text(&#39;Error: ${snapshot.error}&#39;));<br>          } else {<br>            return Padding(padding: EdgeInsets.all(10),<br>            child:AnimationStyles.getAnimatedWidgetForTheme(theme, DynamicUIBuilder(widgetConfigs: snapshot.data!), _controller));<br>          }<br>        },<br>      )</pre><p><strong>Step 4: Create Dynamic UI Based on Server Response<br></strong>To dynamically create the UI based on the server response, you will use the data from the model classes and generate the appropriate widgets.</p><pre>class DynamicUIBuilder extends StatelessWidget {<br>  final List&lt;WidgetConfig&gt; widgetConfigs;<br><br>  DynamicUIBuilder({required this.widgetConfigs});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return ListView.builder(<br>      itemCount: widgetConfigs.length,<br>      itemBuilder: (context, index) {<br>        final config = widgetConfigs[index];<br>        switch (config.type) {<br>          case &#39;text&#39;:<br>            return Text(config.text ?? &#39;&#39;, style: TextStyle(color: Color(int.parse(config.color ?? &#39;0xff000000&#39;))));<br>          case &#39;button&#39;:<br>            return ElevatedButton(<br>              onPressed: () {},<br>              style: ElevatedButton.styleFrom(backgroundColor: Color(int.parse(config.color ?? &#39;0xff000000&#39;))),<br>              child: Text(config.text ?? &#39;&#39;),<br>            );<br>            case &#39;image&#39;: {<br>            return Image.asset(&quot;assets/images/logo.png&quot;);}<br>            case &#39;sizebox&#39;:{<br>            return SizedBox(height: 5,);}<br>            case &#39;textfield&#39;:{<br>            return TextField(<br>              decoration: InputDecoration(border: OutlineInputBorder(),<br>              hintText: config.text),<br>              style: TextStyle(),<br>            );}<br>          default:<br>            return Container();<br>        }<br>      },<br>    );<br>  }<br>}</pre><blockquote>Let’s break down the code:-</blockquote><p>=&gt; Class Definition: Defines a widget that builds its UI based on dynamic configurations.</p><pre>class DynamicUIBuilder extends StatelessWidget {</pre><p>=&gt; Constructor: Accepts a list of WidgetConfig to set up UI elements.</p><pre>final List&lt;WidgetConfig&gt; widgetConfigs;<br>DynamicUIBuilder({required this.widgetConfigs});</pre><p>=&gt;Build Method: Constructs the widget tree using widgetConfigs.</p><pre>@override<br>Widget build(BuildContext context) {</pre><p>=&gt; ListView.builder: Creates a scrollable list of widgets according to the number of configurations.</p><pre>return ListView.builder(<br>  itemCount: widgetConfigs.length,</pre><p>=&gt; ItemBuilder: Builds each list item based on its configuration.</p><pre>itemBuilder: (context, index) {</pre><p>=&gt; Switch Statement: Determines the type of widget to create based on the configuration.</p><pre>switch (config.type) {<br>          case &#39;text&#39;:<br>            return Text(config.text ?? &#39;&#39;, style: TextStyle(color: Color(int.parse(config.color ?? &#39;0xff000000&#39;))));<br>          case &#39;button&#39;:<br>            return ElevatedButton(<br>              onPressed: () {},<br>              style: ElevatedButton.styleFrom(backgroundColor: Color(int.parse(config.color ?? &#39;0xff000000&#39;))),<br>              child: Text(config.text ?? &#39;&#39;),<br>            );<br>            case &#39;image&#39;: {<br>            return Image.asset(&quot;assets/images/logo.png&quot;);}<br>            case &#39;sizebox&#39;:{<br>            return SizedBox(height: 5,);}<br>            case &#39;textfield&#39;:{<br>            return TextField(<br>              decoration: InputDecoration(border: OutlineInputBorder(),<br>              hintText: config.text),<br>              style: TextStyle(),<br>            );}<br>          default:<br>            return Container();<br>        }</pre><blockquote><strong>Note: </strong>Default Case: Returns an empty container for unsupported types.</blockquote><p><strong>Output:-</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qVbBQkfZCXMQgI4RxqMRKg.png" /></figure><p>=&gt; Github link : <a href="https://github.com/Dev-ShivamShrivastava/server_driven">https://github.com/Dev-ShivamShrivastava/server_driven</a></p><p>=&gt; “Quote: ‘Learn something new every day.😊’ Keep coding!😍”</p><blockquote><strong><em>If you find this useful, please hitting the like button and leaving a comment. Your feedback is incredibly valuable to me!</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6affa756b68c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Kotlin Function Questions You Should Know for Interviews]]></title>
            <link>https://medium.com/@shivamshrivastavaad/basic-kotlin-function-questions-you-should-know-for-interviews-d365c227d80e?source=rss-dd7c8af50418------2</link>
            <guid isPermaLink="false">https://medium.com/p/d365c227d80e</guid>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Shivam Shrivastava]]></dc:creator>
            <pubDate>Tue, 16 Jul 2024 21:19:27 GMT</pubDate>
            <atom:updated>2024-07-16T21:19:27.743Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a55ZJAh9shhpCyYZpQhcMw.png" /></figure><blockquote><strong>Higher-Order Functions</strong></blockquote><p>A higher-order function is a function that either takes other functions as parameters or returns a function as its result. Higher-order functions allow for more abstract and reusable code, enabling functions to be more flexible and modular.</p><p>=&gt; Passing Functions as Parameters</p><pre>fun higherOrder(callback:(isHighOrder:Boolean)-&gt;Unit){<br>    callback(true)<br>}<br><br>//In this example, `higherOrder` is a higher-order function because it takes a function operation as a parameter.</pre><p>=&gt; Returning Functions</p><p>Notes: The `higherOrder` function can be called in many ways. You can choose whichever way you prefer.</p><pre>fun main(){<br>  val value =  higherOrder() // Call higherOrder and assign the returned function to &#39;value&#39;<br>    println(value()) // Call the function stored in &#39;value&#39; and print the result<br>}<br>fun higherOrder():()-&gt;Int{<br>    // Return a function that generates a random number between 1 and 20<br>    return { Random.nextInt(1,20)<br>    }<br>}</pre><pre>// Direct Function Call with Double Parentheses<br>fun main(){<br>  val value =  higherOrder()() // Call higherOrder and immediately invoke the returned function<br>    println(value) // Print the result<br>}<br>fun higherOrder():()-&gt;Int{<br>    return { Random.nextInt(1,20) }<br>}</pre><pre>// Using the invoke() Method<br>fun main(){<br>  val value =  higherOrder().invoke() // Call higherOrder and invoke the returned function using invoke()<br>    println(value) // Print the result<br>}<br>fun higherOrder():()-&gt;Int{<br>    return { Random.nextInt(1,20) }<br>}</pre><h4><strong>Benefits of Higher-Order Functions</strong></h4><ol><li><strong>Code Reusability:</strong> Higher-order functions enable the creation of more generic and reusable code.</li><li><strong>Modularity:</strong> Functions can be broken down into smaller, more manageable pieces.</li><li><strong>Abstraction:</strong> They allow for higher levels of abstraction, making the code cleaner and easier to understand.</li></ol><blockquote><strong>Inline Functions</strong></blockquote><p>The inline keyword is used to improve performance by reducing the overhead of higher-order functions. Using inline can help avoid the creation of additional objects and the overhead of function calls.</p><p><strong>How Inline Functions Work :-</strong></p><p>When a function is marked as inline, the Kotlin compiler copies the code of that function and pastes it at each call site. This can lead to more efficient code, especially in scenarios with many small function calls.</p><pre>fun main(){<br>    inlineFunction{<br>      println(it)<br>  }<br><br>}<br>// This is marked as inline, which means the compiler will replace the function call with the function body to reduce overhead.<br>inline fun inlineFunction(callback:(value:Int)-&gt;Unit){<br>// This callback function accepts an integer (value) and returns Unit (i.e., it doesn&#39;t return a value).<br>    callback(Random.nextInt(15,50))<br>}</pre><pre>fun main(){<br>    val value =inlineFunction{it-&gt;<br>      println(it) // Print the generated random number<br>       it.times(2) // Return the random number multiplied by 2<br>  }<br>println(&quot;Callback result: $value&quot;)<br><br>}<br><br>inline fun inlineFunction(callback:(value:Int)-&gt;Int){<br>    callback(Random.nextInt(15,50))<br>}</pre><h3><strong>Limitations</strong></h3><ol><li><strong>Recursion:</strong> Recursive functions cannot be inlined.</li><li><strong>Inline Functions:</strong> Cannot use non-local returns (i.e., returning from the outer function) and have restrictions with recursive calls.<br>Example: -</li></ol><pre>fun main(){<br>    println(&quot;start&quot;)<br>    inlineFunction{it-&gt;<br>      println(it) // Print the generated random number<br>       return // This return exits the main function<br>  }<br>    println(&quot;End&quot;)<br><br>}<br>inline fun inlineFunction(callback:(value:Int)-&gt;Unit){<br>    callback(Random.nextInt(15,50))<br>}<br><br>// Note: A non-local return occurs when you use a return statement within a lambda passed to a higher-order function, effectively trying to exit from the outer function instead of just the lambda.</pre><p>In Kotlin, when dealing with inline functions, you can specify parameters as crossinline or noinline to control how lambdas are treated.</p><p>=&gt; <strong>noinline</strong>: The noinline modifier is used when you want to prevent a specific lambda parameter from being inlined. This means that the lambda will be treated as a regular function and not inlined into the caller&#39;s code.</p><p>=&gt; <strong>crossinline: </strong>The crossinline modifier allows a lambda to be inlined but prevents it from using non-local returns. This means the lambda cannot return from the outer function.</p><blockquote>If you didn’t understand, then let me explain it in a very easy way.</blockquote><p>First, you see the example of noinline.</p><pre>fun main(){<br>    inlineFunction{it-&gt;<br>      println(it)<br>  }<br>}<br>inline fun inlineFunction(noinline callback:(value:Int)-&gt;Unit){<br>    callback(Random.nextInt(15,50))<br>}</pre><p>The ‘<strong>callback</strong>’ function will not behave like an inline function; it will act like a normal function. In other words, if you want a parameterized function to not behave like an inline function, then we use noinline. Meanwhile, the ‘inlineFunction’ will behave as expected for an inline function.<br>``<strong>Note</strong>: Crossinline is the opposite of this.``</p><blockquote><strong>Infix Functions</strong></blockquote><p>n Kotlin, an <strong>infix function</strong> is a function that can be called using infix notation, allowing for a more readable and expressive syntax. It allows you to call a function without using the traditional dot (.) and parentheses (()).</p><h4>Characteristics of Infix Functions</h4><ol><li><strong>Single Parameter</strong>: Infix functions must have a single parameter.</li><li><strong>Member or Extension Function</strong>: They can be either member functions or extension functions.</li><li><strong>Infix Notation</strong>: You call them using the infix notation without parentheses.</li></ol><p>Example with <strong>extension</strong> function:-</p><pre>fun main(){<br>    println(10 add 20)<br>}<br><br>infix fun Int.add(value: Int): Int {<br>    return this + value<br>}</pre><p>Example with <strong>member</strong> function:-</p><pre>fun main(){<br>    val addition1=Addition(1, 2)<br>    val addition2 =Addition(3, 4)<br>    val result=addition1 add addition2<br>    println(&quot;Resulting Point: (${result.x}, ${result.y})&quot;)<br>}<br><br>class Addition(val x:Int=0,val y:Int=0){<br>    infix fun add(obj:Addition):Addition{<br>        return Addition(this.x+obj.x,this.y+obj.y )<br>    }<br>}  </pre><h4>Limitations</h4><ul><li>Infix functions can only take one parameter.</li></ul><p>“Quote: ‘Learn something new every day.😊’ Keep coding!😍”</p><blockquote><strong><em>If you find this useful, please hitting the like button and leaving a comment. Your feedback is incredibly valuable to me!</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d365c227d80e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL with MVVM Architecture in Android.]]></title>
            <link>https://medium.com/@shivamshrivastavaad/graphql-with-mvvm-architecture-in-android-e175544762a5?source=rss-dd7c8af50418------2</link>
            <guid isPermaLink="false">https://medium.com/p/e175544762a5</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack]]></category>
            <dc:creator><![CDATA[Shivam Shrivastava]]></dc:creator>
            <pubDate>Sun, 14 Jul 2024 08:10:23 GMT</pubDate>
            <atom:updated>2024-07-14T09:05:30.912Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9cgVDcKsHMED2cVcWp29Kw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*Cyk8UYvaehkomBpC8cBK1A.png" /></figure><p><strong>What is GraphQL ?<br></strong>GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. It enables clients to request exactly the data they need, which minimizes the amount of data transferred over the network and makes apps faster and more efficient. Instead of multiple endpoints like in REST, GraphQL uses a single endpoint to deliver flexible and precise responses, allowing clients to specify their exact requirements. This ensures that they receive only the necessary data, making API interactions more efficient and adaptable to changing needs.</p><p><strong>Advantages:</strong></p><ul><li><strong>Precise Data Fetching:</strong> Clients can request exactly the data they need, reducing over-fetching and under-fetching.</li><li><strong>Single Endpoint:</strong> All interactions are handled through a single endpoint, simplifying API design and usage.</li><li><strong>Efficient Data Loading:</strong> Supports batching and parallel loading of data, which can reduce the number of network requests.</li></ul><p><strong>Disadvantages:</strong></p><ul><li><strong>Complexity:</strong> Setting up and maintaining a GraphQL server can be more complex compared to REST.</li><li><strong>Learning Curve:</strong> Developers need to learn GraphQL syntax and concepts, which can be a barrier to adoption.</li><li><strong>Caching Challenges:</strong> Traditional HTTP caching mechanisms do not work as effectively with GraphQL. Custom caching strategies are often required.</li></ul><h3>Differences Between GraphQL and RESTful API</h3><blockquote><strong>Data Fetching:</strong></blockquote><ul><li><strong>GraphQL:</strong> Clients can request exactly the data they need in a single query, reducing over-fetching and under-fetching.</li><li><strong>REST:</strong> Each endpoint returns a fixed data structure, which can lead to over-fetching (too much data) or under-fetching (too little data).</li></ul><blockquote><strong>Endpoints:</strong></blockquote><ul><li><strong>GraphQL:</strong> Operates on a single endpoint that handles all types of requests (queries and mutations).</li><li><strong>REST:</strong> Uses multiple endpoints for different resources and actions (e.g., /users, /posts).</li></ul><blockquote><strong>Flexibility:</strong></blockquote><ul><li><strong>GraphQL:</strong> Highly flexible, allowing clients to define the structure of the response. Clients can nest related resources within a single query.</li><li><strong>REST:</strong> Less flexible, with a fixed response structure. Requires multiple requests for related resources.</li></ul><h4><strong>The theory is enough now; let’s do some practical work. Just stay with me! 😄</strong></h4><blockquote><em>For better understanding, I have created a simple project in which I used Jetpack components such as Coroutine, Flow, Hilt, and View Binding. I am also attaching the source code link and the documentation link that I followed during the implementation.</em></blockquote><h4>Add Apollo GraphQL library in your app:-</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*80cv4Dhwr4eQhFZeBvqmeg.png" /></figure><p>In your project libs.versions.toml (Version Catalog) add following:-</p><pre>graphql =&quot;3.7.3&quot;<br>apolloapi =&quot;3.7.3&quot;<br>apolloruntime =&quot;3.7.3&quot;<br><br>apollo-runtime = { group = &quot;com.apollographql.apollo3&quot;, name = &quot;apollo-runtime&quot;, version.ref = &quot;apolloruntime&quot; }<br>apollo-api = { group = &quot;com.apollographql.apollo3&quot;, name = &quot;apollo-api&quot;, version.ref = &quot;apolloapi&quot; }<br><br>apollo-graph-ql = { id = &quot;com.apollographql.apollo3&quot;, version.ref = &quot;graphql&quot; }</pre><p>open <strong>project</strong> build.gradle.kts add following:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oGIgffjlzYZht2DctmsmNw.png" /></figure><pre>//Graph ql<br>alias(libs.plugins.apollo.graph.ql) apply false</pre><p>then open <strong>app</strong> build.gradle.kts add following:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5BWh0qXefoKL4mR4TVQ5Fw.png" /></figure><pre>alias(libs.plugins.apollo.graph.ql)<br><br>apollo {<br>        useVersion2Compat()<br>    }<br><br>    //Graph ql<br>    implementation(libs.apollo.runtime)<br>    implementation(libs.apollo.api)</pre><blockquote><em>Notes:- Suppose you have more than one schemas. In that case, you have to define both schemas in the </em><em>app/build.gradle.kts file as follows:-</em></blockquote><pre> apollo {<br>        service(&quot;service1&quot;) {<br>            sourceFolder.set(&quot;com/indigo/graph&quot;)<br>            packageName.set(&quot;com.indigo.graph&quot;)<br>            schemaFile.set(file(&quot;src/main/graphql/com/indigo/graph/schema.graphqls&quot;))<br>        }<br>        service(&quot;service2&quot;) {<br>            sourceFolder.set(&quot;com/indigo/pokemon&quot;)<br>            packageName.set(&quot;com.indigo.pokemon&quot;)<br>            schemaFile.set(file(&quot;src/main/graphql/com/indigo/pokemon/schema.graphqls&quot;))<br>        }<br>       // useVersion2Compat()<br>    }</pre><p><strong>=&gt; Now the time has come when we need to add the schema to your project. To add the schema, we need to run one command. </strong><a href="https://dashboard.stepzen.com/explorer?endpoint=https://beta.pokeapi.co/graphql/v1beta&amp;query=query%20%7B%20pokemon_v2_pokemon%28limit%3A%2010%29%20%7B%20height%20id%20name%20order%20pokemon_species_id%20%7D%20%7D"><strong>Schema Link</strong></a></p><pre>mkdir -p app/src/main/graphql/com/indigo/pockemon/ <br>./gradlew :app:downloadApolloSchema - endpoint=&#39;https://beta.pokeapi.co/graphql/v1beta&#39; - schema=&#39;app/src/main/graphql/com/indigo/pockemon/schema.graphqls&#39;</pre><p><strong>Let’s break down the command:-</strong></p><p><strong>Create the Directory =&gt; </strong>mkdir -p app/src/main/graphql/com/indigo/pockemon/</p><p><strong>Download Schema</strong> =&gt; ./gradlew :app:downloadApolloSchema — endpoint=’https://beta.pokeapi.co/graphql/v1beta&#39; — schema=’app/src/main/graphql/com/indigo/pockemon/schema.graphqls’</p><p><strong><em>Notes:- </em></strong><em>Make sure to use your own directory and schema in the command.</em></p><h4><strong>Now we will add a plugin that will help us create GraphQL files. In these files, we will write our queries.</strong></h4><ul><li>On <strong>Windows/Linux</strong>: Go to File &gt; Settings.</li><li>On <strong>Mac</strong>: Go to Android Studio &gt; Preferences.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ycB32pr2G7mtYWBeMPIrzQ.png" /><figcaption>Link:- <a href="https://plugins.jetbrains.com/plugin/8097-graphql">https://plugins.jetbrains.com/plugin/8097-graphql</a></figcaption></figure><blockquote><strong>Let’s write our first query:</strong></blockquote><h4>Create a New GraphQL File</h4><ul><li><strong>Right-click</strong> on the directory.</li><li>Select <strong>New</strong> &gt; <strong>File</strong>.</li><li>Name your file, for example, Pokemon.graphql</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IgmhuOXMyCUzbAthcAY_6w.png" /></figure><h4>In the created file, write your query</h4><p>Example:-</p><pre>query Pokemon{<br>    pokemon_v2_pokemon(limit: 20) {<br>        height<br>        id<br>        name<br>        order<br>        pokemon_species_id<br>    }<br>}</pre><blockquote><strong>Create an Apollo Client.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5FsYPDsypti2IvXxLsdCg.png" /><figcaption>Apollo client with Hilt</figcaption></figure><pre>ApolloClient.Builder()<br>            .serverUrl(baseUrl)<br>            .build()</pre><blockquote><strong>Create a Repository file</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iP25o7mdCeYhp1gnPMv5BA.png" /></figure><pre><br>class Repository @Inject constructor(val apolloClient: ApolloClient) {<br><br><br>    suspend fun &lt;D : Query.Data&gt; makeApiCall(query: Query&lt;D&gt;): Flow&lt;NetworkProcess&lt;D?&gt;&gt; =<br>        flow {<br>            emit(NetworkProcess.Loading)<br>            try {<br>                val response = apolloClient.query(query).execute()<br>                emit(NetworkProcess.Success(response.data))<br>            } catch (e: ApolloException) {<br>                emit(NetworkProcess.Failure(e.message ?: &quot;Something went wrong&quot;))<br>            } catch (e: Exception) {<br>                emit(NetworkProcess.Failure(e.message ?: &quot;Something went wrong&quot;))<br>            }<br>        }.flowOn(Dispatchers.IO)<br><br><br>}</pre><p>Now call this repository function from the ViewModel with your query like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fIBhzxQrnVeMOGMdMI10Ew.png" /></figure><pre>@HiltViewModel<br>class MainVM @Inject constructor(val repository: Repository) : ViewModel() {<br><br>    val pokemonList = MutableSharedFlow&lt;List&lt;Pokemon&gt;&gt;()<br>    val loader = MutableSharedFlow&lt;Boolean&gt;()<br><br>    init {<br>        getPokemon()<br>    }<br><br>     fun getPokemon() {<br><br>        CoroutineScope(Dispatchers.IO).launch {<br>            loader.emit(true)<br>            repository.makeApiCall(PokemonQuery()).collect {<br>                when (it) {<br><br>                    is NetworkProcess.Success -&gt; {<br>                        loader.emit(false)<br>                        val list = it.data?.pokemon_v2_pokemon?.map { it.toSimplePokemon() }<br>                        pokemonList.emit( list ?: emptyList())<br>                    }<br>                    is NetworkProcess.Failure -&gt; {<br><br>                    }<br><br>                    is NetworkProcess.Loading -&gt; {<br>                    }<br>                }<br>            }<br>        }<br>    }<br><br>  <br>}</pre><blockquote><strong>Create a Mappers File</strong> =&gt; The mapper function is required to transform data from the GraphQL response format to a usable format in your application. It handles nullability by providing default values, preventing null pointer exceptions. This encapsulates the conversion logic, improving code readability and maintainability.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_744W14w8tja-0fu9izMFg.png" /></figure><pre>fun PokemonQuery.Pokemon_v2_pokemon.toSimplePokemon(): Pokemon {<br>    return Pokemon(<br>        height = height?:-1 ,<br>        name = name,<br>        id = id,<br>        order = order ?: -1,<br>    )<br>}</pre><blockquote><strong>Finally, set the data on the UI.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ni70ZSctnRuqRLVzuPL9tg.png" /></figure><pre>@AndroidEntryPoint<br>class MainActivity : AppCompatActivity() {<br><br>    private val mainVM: MainVM by viewModels()<br>    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }<br>    private val adapter by lazy { PokemonAdapter() }<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        enableEdgeToEdge()<br>        setContentView(binding.root)<br>        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -&gt;<br>            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())<br>            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)<br>            insets<br>        }<br>        binding.rvPokemon.adapter = adapter<br>        lifecycleScope.launch {<br>            supervisorScope {<br>                launch {<br>                    mainVM.pokemonList.collect {<br>                        if(it.isNotEmpty()){<br>                            adapter.setData(it)<br>                        }<br>                    }<br>                }<br>                launch {<br>                    mainVM.loader.collect{<br>                        if(it){<br>                            binding.progressBar.visibility = View.VISIBLE<br>                        }else{<br>                            binding.progressBar.visibility = View.GONE<br>                        }<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><strong>Output:-</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*rQetqXgoq_gpL7BqGH2Bmw.gif" /></figure><p>Project Source code -&gt; <a href="https://github.com/Dev-ShivamShrivastava/GraphQL">https://github.com/Dev-ShivamShrivastava/GraphQL</a></p><p>Apollo Doc -&gt;<a href="https://www.apollographql.com/docs/kotlin/"> https://www.apollographql.com/docs/kotlin/</a></p><p>“Quotes: ‘Learn something new every day.😊’ Keep coding!😍”</p><blockquote><strong>If you find this useful, please support us by hitting the like button and leaving a comment. Your feedback is incredibly valuable to me!</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e175544762a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>