<?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 Keval Kanpariya on Medium]]></title>
        <description><![CDATA[Stories by Keval Kanpariya on Medium]]></description>
        <link>https://medium.com/@kevalkanpariya5051?source=rss-2ca056449a1c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y6Fv_V24kMDXiHw3SV9O3Q.jpeg</url>
            <title>Stories by Keval Kanpariya on Medium</title>
            <link>https://medium.com/@kevalkanpariya5051?source=rss-2ca056449a1c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:20:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kevalkanpariya5051/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[Streamlining Android Builds: My Journey with Fastlane and GitHub Actions]]></title>
            <link>https://medium.com/@kevalkanpariya5051/streamlining-android-builds-my-journey-with-fastlane-and-github-actions-c8b973140327?source=rss-2ca056449a1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8b973140327</guid>
            <category><![CDATA[fastlane]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Keval Kanpariya]]></dc:creator>
            <pubDate>Wed, 22 Jan 2025 12:57:33 GMT</pubDate>
            <atom:updated>2025-01-25T04:29:36.597Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*-BXRJi7b50B6ds3MX0GYGw.png" /></figure><p>Recently, I delved into using Fastlane with GitHub Actions for the first time, aiming to automate the deployment of our Android app to the Play Store and distribute builds to Firebase App Distribution. This new venture opened up a world of efficiency and convenience that I hadn’t fully tapped into before. I had the opportunity to apply this workflow during my tenure as an Open Source Contributor for Piramal Swasthya under the C4GT Community Program.</p><h3>Crafting an Efficient Workflow</h3><p>The task at hand was to create a robust, automated workflow for building and distributing our Android applications. The goal was to ensure that every push to our develop branch would trigger a series of events, from code checkout to distributing the build to Firebase App Distributions or the Google Play Store.</p><h3>Step-by-Step Breakdown:</h3><h4>1. Defining Workflow Triggers</h4><p>My journey began with setting up the workflow to trigger on specific events — pushes and pull requests to the develop branch, and manual triggers using workflow_dispatch.</p><pre>name: Android Build and Distribute<br><br>on:<br>  workflow_dispatch:<br>  push:<br>    branches:<br>      - develop<br>  pull_request:<br>    branches:<br>      - develop</pre><h4>2. Setting Up the Environment</h4><p>Environment variables such as the main project module, repository name, and current date were configured to ensure consistency across the workflow.</p><pre>env:<br>  main_project_module: app<br>  repository_name: FLW-Mobile-App<br>  date_today: ${{ github.event.head_commit.timestamp }}</pre><h4>3. Job Definitions</h4><p>I created reusable job definitions for different environments like saksham_stag and saksham_uat, encapsulating common tasks in a separate workflow file.</p><pre>jobs:<br>  saksham_stag_job:<br>    uses: ./.github/workflows/build-distribute.yml<br>    with:<br>      environment: SAKSHAM_STAG<br>      variant: SakshamStag<br>      build_type: debug<br>    secrets: inherit<br><br>  saksham_uat_job:<br>    uses: ./.github/workflows/build-distribute.yml<br>    with:<br>      environment: SAKSHAM_UAT<br>      variant: SakshamUat<br>      build_type: debug<br>    secrets: inherit<br><br>  niramay_production_job:<br>    uses: ./.github/workflows/build-distribute.yml<br>    with:<br>      environment: NIRAMAY_PRODUCTION<br>      variant: Niramay<br>      build_type: release<br>    secrets: inherit<br><br>  xushrukha_production_job:<br>    uses: ./.github/workflows/build-distribute.yml<br>    with:<br>      environment: XUSHRUKHA_PRODUCTION<br>      variant: Xushrukha<br>      build_type: release<br>    secrets: inherit</pre><h4>4. Building the Reusable Workflow</h4><p>This included essential steps like checking out the code, setting up the JDK, Android SDK, NDK, and CMake, and configuring the Ruby environment. Each of these steps played a crucial role in preparing the build environment.</p><pre>jobs:<br>  build:<br>    runs-on: ubuntu-latest<br>    environment: ${{ inputs.environment }}<br><br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v4<br><br>      - name: Set up JDK<br>        uses: actions/setup-java@v4<br>        with:<br>          distribution: &#39;zulu&#39;<br>          java-version: &#39;17&#39;<br><br>      - name: Set up Android SDK<br>        uses: android-actions/setup-android@v2<br><br>      - name: Set up Android NDK<br>        uses: nttld/setup-ndk@v1.5.0<br>        with:<br>          ndk-version: r27c<br>          link-to-sdk: true<br><br>      - name: Install CMake<br>        uses: jwlawson/actions-setup-cmake@v1<br>        with:<br>          cmake-version: &#39;3.31.1&#39;<br><br>      - name: Set up ruby env<br>        uses: ruby/setup-ruby@v1<br>        with:<br>          ruby-version: 2.7.2<br>          bundler-cache: true<br><br>      - name: Verify Ruby installation<br>        run: ruby -v</pre><h4>5. Decoding Secrets</h4><p>To maintain security, we decoded various secrets such as google-services.json, Firebase credentials, and Google Play JSON key based on the environment and build type.</p><pre>      - name: Decode google-services.json for NIRAMAY_PRODUCTION<br>        if: inputs.environment == &#39;NIRAMAY_PRODUCTION&#39;<br>        run: |<br>          echo &quot;${{ secrets.GOOGLE_SERVICES_JSON_NIRAMAY_PRODUCTION }}&quot; | base64 --decode &gt; ./app/google-services.json || exit 1<br><br>      - name: Decode google-services.json for XUSHRUKHA_PRODUCTION<br>        if: inputs.environment == &#39;XUSHRUKHA_PRODUCTION&#39;<br>        run: |<br>          echo &quot;${{ secrets.GOOGLE_SERVICES_JSON_XUSHRUKHA_PRODUCTION }}&quot; | base64 --decode &gt; ./app/google-services.json || exit 1<br><br>      - name: Decode generic google-services.json for other environments<br>        if: inputs.environment != &#39;NIRAMAY_PRODUCTION&#39; &amp;&amp; inputs.environment != &#39;XUSHRUKHA_PRODUCTION&#39;<br>        run: |<br>          echo &quot;${{ secrets.GOOGLE_SERVICES_JSON_GENERIC }}&quot; | base64 --decode &gt; ./app/google-services.json || exit 1<br><br>      - name: Decode Firebase Credentials<br>        run: |<br>          variant=${{ inputs.variant }}<br>          case &quot;$variant&quot; in<br>            SakshamStag|SakshamUat|Saksham)<br>              echo &quot;${{ secrets.FIREBASE_CREDENTIALS_JSON_SAKSHAM_ASSAM }}&quot; | base64 --decode &gt; firebase_credentials.json<br>              ;;<br>            Niramay)<br>              echo &quot;${{ secrets.FIREBASE_CREDENTIALS_JSON_UTPRERONA_NIRAMAY }}&quot; | base64 --decode &gt; firebase_credentials.json<br>              ;;<br>            Xushrukha)<br>              echo &quot;${{ secrets.FIREBASE_CREDENTIALS_JSON_UTPRERONA_XUSHRUKHA }}&quot; | base64 --decode &gt; firebase_credentials.json<br>              ;;<br>            *)<br>              echo &quot;Unknown variant: $variant&quot;<br>              exit 1<br>              ;;<br>          esac<br><br>      - name: Decode Google Play JSON key<br>        if: ${{ inputs.build_type == &#39;release&#39; }}<br>        run: |<br>          echo &quot;${{ secrets.GOOGLE_PLAY_JSON_KEY }}&quot; | base64 --decode &gt; ./google_play_service_account.json<br><br>      - name: Create local.properties<br>        run: echo &quot;sdk.dir=$ANDROID_SDK_ROOT&quot; &gt; local.properties<br><br>      - name: Decode keystore<br>        run: |<br>          echo &quot;${{ secrets.KEYSTORE_FILE }}&quot; | base64 --decode &gt; ${{ github.workspace }}/keystore.jks<br>          echo &quot;Keystore path: ${{ github.workspace }}/keystore.jks&quot;</pre><h4>6. Building and Distributing the App</h4><p>I utilized Fastlane to build and distribute the app. Separate lanes were created for debug and release builds, each tailored to handle specific tasks like setting version codes, signing the APK, and uploading to Firebase or Google Play Store.</p><p><em>Github action configuration:</em></p><pre>- name: Build and Distribute app to Firebase<br>        id: build-and-distribute<br>        run: |<br>          # Set app URLs used in the codebase<br>          export ENCRYPTED_PASS_KEY=${{ secrets.ENCRYPTED_PASS_KEY }}<br>          export ABHA_CLIENT_ID=${{ secrets.ABHA_CLIENT_ID }}<br>          export ABHA_CLIENT_SECRET=${{ secrets.ABHA_CLIENT_SECRET }}<br>          export BASE_TMC_URL=${{ secrets.BASE_TMC_URL }}<br>          export BASE_ABHA_URL=${{ secrets.BASE_ABHA_URL }}<br>          export ABHA_TOKEN_URL=${{ secrets.ABHA_TOKEN_URL }}<br>          export ABHA_AUTH_URL=${{ secrets.ABHA_AUTH_URL }}<br>          <br>          # Set app release version signing credentials<br>          export KEYSTORE_PASSWORD=$(echo ${{ secrets.KEYSTORE_PASSWORD }} | base64 --decode)<br>          export KEY_ALIAS=${{ secrets.KEY_ALIAS }}<br>          export KEY_PASSWORD=$(echo ${{ secrets.KEY_PASSWORD }} | base64 --decode)<br>          <br>          # Set Firebase App ID for Distribution<br>          export FIREBASE_APP_ID=${{ secrets.FIREBASE_APP_ID }}<br><br>          if [ &quot;${{ inputs.build_type }}&quot; == &quot;debug&quot; ]; then<br>            bundle exec fastlane build_and_distribute_debug variant:${{ inputs.variant }}<br>          else<br>            bundle exec fastlane build_and_distribute_release variant:${{ inputs.variant }}<br>          fi</pre><p><em>Securely manage and access sensitive information, such as API keys and secrets:</em></p><p>I opted for JNI configuration to manage sensitive data, offering several key advantages. JNI isolates secrets within a native library, enhancing security against reverse engineering. It can potentially improve performance and memory usage, while also simplifying code maintenance and reducing the risk of accidental data exposure compared to methods like BuildConfig, DataStore, and Encrypted SharedPreferences.</p><p><em>JNI Configuration (</em><strong><em>native-lib.cpp):</em></strong></p><p>The native-lib.cpp file contains the native C++ code that will be called from Kotlin code. Here&#39;s a simplified example:</p><pre>#include &lt;jni.h&gt;<br>#include &lt;string&gt;<br>#include &lt;android/log.h&gt;<br><br>// JNI functions<br>extern &quot;C&quot; JNIEXPORT jstring JNICALL<br>Java_org_piramalswasthya_sakhi_utils_KeyUtils_encryptedPassKey(JNIEnv *env, jobject thiz) {<br>    std::string encryptedPassKey = ENCRYPTED_PASS_KEY;<br>    return env-&gt;NewStringUTF(encryptedPassKey.c_str());<br>}<br><br>extern &quot;C&quot; JNIEXPORT jstring JNICALL<br>Java_org_piramalswasthya_sakhi_utils_KeyUtils_abhaClientSecret(JNIEnv *env, jobject thiz) {<br>    std::string abhaClientSecret = ABHA_CLIENT_SECRET;<br>    return env-&gt;NewStringUTF(abhaClientSecret.c_str());<br>}<br><br># ... and more</pre><p><em>CMake Configuration (</em><strong><em>CMakeLists.txt):-</em></strong></p><p>The CMakeLists.txt file is crucial for building the native library. It handles: Fetching Environment Variables,Passing Values to the Compiler, Building the Shared Library.</p><pre>cmake_minimum_required(VERSION 3.11)<br>project(Sakhi LANGUAGES CXX)<br><br># Fetch environment variables<br>set(ENCRYPTED_PASS_KEY &quot;$ENV{ENCRYPTED_PASS_KEY}&quot;)<br>set(ABHA_CLIENT_SECRET &quot;$ENV{ABHA_CLIENT_SECRET}&quot;)<br>set(ABHA_CLIENT_ID &quot;$ENV{ABHA_CLIENT_ID}&quot;)<br>set(BASE_TMC_URL &quot;$ENV{BASE_TMC_URL}&quot;)<br>set(BASE_ABHA_URL &quot;$ENV{BASE_ABHA_URL}&quot;)<br>set(ABHA_TOKEN_URL &quot;$ENV{ABHA_TOKEN_URL}&quot;)<br>set(ABHA_AUTH_URL &quot;$ENV{ABHA_AUTH_URL}&quot;)<br>set(CHAT_URL &quot;$ENV{CHAT_URL}&quot;)<br><br># Pass the values to the compiler using add_definitions<br>add_definitions(<br>        -DENCRYPTED_PASS_KEY=\&quot;${ENCRYPTED_PASS_KEY}\&quot;<br>        -DABHA_CLIENT_SECRET=\&quot;${ABHA_CLIENT_SECRET}\&quot;<br>        -DABHA_CLIENT_ID=\&quot;${ABHA_CLIENT_ID}\&quot;<br>        -DBASE_TMC_URL=\&quot;${BASE_TMC_URL}\&quot;<br>        -DBASE_ABHA_URL=\&quot;${BASE_ABHA_URL}\&quot;<br>        -DABHA_TOKEN_URL=\&quot;${ABHA_TOKEN_URL}\&quot;<br>        -DABHA_AUTH_URL=\&quot;${ABHA_AUTH_URL}\&quot;<br>        -DCHAT_URL=\&quot;${CHAT_URL}\&quot;<br>)<br><br># Define the library name<br>set(LIBRARY_NAME &quot;sakhi&quot;)<br><br># Add the native-lib.cpp as the source file for the shared library<br>add_library(<br>        ${LIBRARY_NAME}<br>        SHARED<br>        native-lib.cpp<br>)<br><br># Find the log library<br>find_library(<br>        log-lib<br>        log<br>)<br><br># Specifies libraries CMake should link to your target library.<br>target_link_libraries(<br>        ${LIBRARY_NAME}<br>        ${log-lib}<br>)</pre><p><em>Accessing Sensitive Information:-</em> In Kotlin code, I created a KeyUtils object class to interact with the native library:</p><pre><br>object KeyUtils {<br><br>    private const val NATIVE_JNI_LIB_NAME = &quot;sakhi&quot;<br><br>    init {<br>        try {<br>            System.loadLibrary(NATIVE_JNI_LIB_NAME)<br>        } catch (e: UnsatisfiedLinkError) {<br>            throw RuntimeException(&quot;Failed to load native library: $NATIVE_JNI_LIB_NAME&quot;)<br>        }<br><br>    }<br><br>    external fun encryptedPassKey(): String<br><br>    //.. more<br>}</pre><p>The external fun declaration allowing to call the native C++ function (encryptedPassKey) from Kotlin code.</p><p><em>Uploading APKs to Artifacts and Pushing to Releases:</em></p><pre>- name: Upload APKs<br>        uses: actions/upload-artifact@v4<br>        with:<br>          name: FLW-Mobile-App - APK(s) ${{ inputs.variant }} generated<br>          path: |<br>             ${{ inputs.build_type == &#39;debug&#39; &amp;&amp; &#39;app/build/outputs/apk/**/&#39; + inputs.build_type + &#39;/*.apk&#39; || &#39;app/build/outputs/bundle/**/&#39; +inputs.build_type + /*.aab&#39; }}<br><br>      - name: Push to Releases<br>        if: inputs.variant == &#39;release&#39;<br>        uses: ncipollo/release-action@v1<br>        with:<br>          artifacts: &quot;app/build/outputs/bundle/**/${{ inputs.build_type }}/release/*.aab&quot;<br>          tag: v${{ env.version }}-${{ inputs.environment }}-${{ github.run_number }}<br>          token: ${{ secrets.GITHUB_TOKEN }}</pre><p><em>Fastlane lane for Build and Distribute Debug APK to Firebase App Distributions:</em></p><pre>default_platform(:android)<br>platform :android do<br><br>  desc &quot;Build and Distribute Debug APK to Firebase App Distributions&quot;<br>  lane :build_and_distribute_debug do |options|<br><br>   latest_release = firebase_app_distribution_get_latest_release(<br>      app: ENV[&#39;FIREBASE_APP_ID&#39;],<br>      service_credentials_file: &quot;firebase_credentials.json&quot;<br>   )<br>   new_version_code = latest_release[:buildVersion].to_i + 1<br>   current_version_name = android_get_version_name<br>   new_version_name = &quot;#{new_version_code}.0.0&quot;<br><br>    File.open(&quot;../version/version.properties&quot;, &quot;w&quot;) do |file|<br>        file.write(&quot;VERSION=#{new_version_name}&quot;)<br>    end<br><br>    # Build the debug variant<br>    gradle(<br>      task: &quot;clean assemble#{options[:variant]}Debug&quot;<br>    )<br><br>    # Distribute to Firebase App Distribution for Stag and UAT<br>    firebase_app_distribution(<br>      app: ENV[&#39;FIREBASE_APP_ID&#39;],<br>      service_credentials_file: &quot;firebase_credentials.json&quot;,<br>      release_notes_file: &quot;FirebaseAppDistributionConfig/release_notes.txt&quot;,<br>      groups_file: &quot;FirebaseAppDistributionConfig/groups.txt&quot;,<br>      debug: true<br>    )<br>  end</pre><p>Additionally, for Play Store deployment, I created lanes to handle signing the APK and uploading it to the internal track.</p><pre>  desc &quot;Build, Sign, and Distribute Release Bundle to Play Store&quot;<br>  lane :build_and_distribute_release do |options|<br>    keystore_path = File.expand_path(&#39;../keystore.jks&#39;)<br>    package_name = get_package_name(options[:variant])<br>    new_version_code = latest_googleplay_version_code(package_name) + 1<br>    current_version_name = android_get_version_name<br>    new_version_name = &quot;#{new_version_code}.0.0&quot;<br><br><br>    # Log the new version code and version name<br>    puts &quot;New version code: #{new_version_code}&quot;<br>    puts &quot;New version name: #{new_version_name}&quot;<br>    # update version<br>    File.open(&quot;../version/version.properties&quot;, &quot;w&quot;) do |file|<br>        file.write(&quot;VERSION=#{new_version_name}&quot;)<br>    end<br><br>    gradle(<br>          task: &quot;clean bundle#{options[:variant]}Release&quot;,<br>          properties: {<br>            &quot;android.injected.signing.store.file&quot; =&gt; keystore_path,<br>            &quot;android.injected.signing.store.password&quot; =&gt; &quot;#{ENV[&#39;KEYSTORE_PASSWORD&#39;]}&quot;,<br>            &quot;android.injected.signing.key.alias&quot; =&gt; &quot;#{ENV[&#39;KEY_ALIAS&#39;]}&quot;,<br>            &quot;android.injected.signing.key.password&quot; =&gt; &quot;#{ENV[&#39;KEY_PASSWORD&#39;]}&quot;,<br>          }<br>      )<br><br>    upload_to_play_store(<br>          track: &quot;internal&quot;,<br>          skip_upload_images: true,<br>          skip_upload_screenshots: true,<br>          release_status: &quot;draft&quot;,<br>          version_code: new_version_code,<br>          package_name: package_name<br>    )<br>  end</pre><h4>7. Required Fastlane Plugins and Necessary Configuration</h4><p>To make this workflow work seamlessly, several plugins and configurations are required:</p><p><strong>Fastlane Plugins:</strong></p><ul><li>fastlane-plugin-firebase_app_distribution</li><li>fastlane-plugin-google_play_track_version_codes</li></ul><p>Add these plugins to your Pluginfileor manually install using fastlane add_plugin {plugin name}cmd on terminal:</p><pre>gem &#39;fastlane-plugin-firebase_app_distribution&#39;<br>gem &#39;fastlane-plugin-google_play_track_version_codes&#39;</pre><p><strong>Gradle Configuration:</strong> Ensure your build.gradle files are correctly configured to handle different build variants and signing configurations.</p><pre>apply from: &#39;../versioning.gradle&#39; #your path to versioning.gradle file(in this case it&#39;s located in root directory)<br><br>android {<br>    ..<br>    defaultConfig {<br>        ..<br>        versionCode buildVersionCode()<br>        versionName buildVersionName()<br>    }<br>}</pre><p>Define Version in version.properties</p><pre>VERSION=X.0.0 #define in version.properties file(in this case it&#39;s located in version directory inside the Root Project)</pre><h3>Transforming Development Efficiency</h3><p>The implementation of this automated workflow brought about a significant transformation in our development process:</p><p><strong>Consistency and Reliability</strong>: The workflow ensured that each build followed a consistent process, reducing the chances of human error and increasing the reliability of our releases.</p><p><strong>Time Savings</strong>: Automation freed up valuable developer time, allowing the team to focus on more critical tasks such as feature development and bug fixing.</p><p><strong>Faster Releases</strong>: With the workflow handling the entire build and release process, we were able to push out updates faster, keeping our users satisfied and our app up-to-date.</p><p><strong>Improved Security:</strong> The JNI configuration played a crucial role by securely managing sensitive data, reducing the risk of data breaches and enhancing the overall security posture of the applications.</p><p><strong>Enhanced Collaboration</strong>: The standardized process made it easier for team members to collaborate, as everyone followed the same steps and knew what to expect from each build.</p><h3>Real-World Application: Piramal Swasthya</h3><p>During my time with Piramal Swasthya, I leveraged this workflow to streamline the build and release processes for two Android apps (FLW &amp; HLW). This resulted in faster release cycles and successful management of six releases across different environments (Stag, UAT, Production). Additionally, implementing efficient configuration management for multiple product flavors and integrating security best practices through JNI configuration enhanced the overall workflow’s effectiveness.</p><p>Specifically, I deployed saksham_stag, saksham_uat, hlw_stag, and hlw_uat app varients on Firebase App Distributions, while Niramay and Xushrukha were deployed on the Play Store&#39;s internal track.</p><h3>Conclusion</h3><p>Embracing automation in our build and release process, coupled with the secure management of sensitive data through JNI configuration, was a game-changer. It not only enhanced our efficiency but also allowed us to deliver high-quality updates to our users more swiftly and reliably. My experience with tools like GitHub Actions and Fastlane, combined with the strategic use of JNI, has been a testament to the power of automation in transforming the way we work.</p><h3><strong>Acknowledge</strong></h3><p>I would like to express my sincere gratitude to <strong><em>Mithun James</em></strong>(<a href="https://www.linkedin.com/in/dr-mithun-james/">https://www.linkedin.com/in/dr-mithun-james/</a>) and <strong><em>Nikhil Fegade</em></strong> from Piramal Swasthya Research and Management Institute for their invaluable guidance and mentorship throughout this journey</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8b973140327" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ktor Client is a Network Client Provider for Android]]></title>
            <link>https://medium.com/@kevalkanpariya5051/ktor-client-is-a-network-client-provider-for-android-23b5803d15b2?source=rss-2ca056449a1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/23b5803d15b2</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[koin]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ktor-client]]></category>
            <dc:creator><![CDATA[Keval Kanpariya]]></dc:creator>
            <pubDate>Fri, 08 Mar 2024 16:13:10 GMT</pubDate>
            <atom:updated>2024-03-08T16:13:10.018Z</atom:updated>
            <content:encoded><![CDATA[<p>In Android, there are several ways available to perform network calls. but nowadays most developers are using Retrofit Framework combined with OKHttp Client. One of the reasons is that by using Native Framework, you will get access to the input stream, read and manage bytes, and closing InputConnection is a headache for every single API Call. Another reason for using OKHttp Client is that you can implement WebSocket Functionality along with REST API Call.</p><p>Recently Ktor Client came up with coroutine support for API calls to support multiplatform(e.g., IOS, Android, Web, Desktop). it’s developed using Kotlin. so the coroutine feature gives us efficient Multithreading operation.</p><h3><strong>Advantages of Ktor-Client:</strong></h3><p>1. <strong><em>Convenience:</em></strong> Easy to pass headers, parameters, and URLs in the function body itself, improving the Traditional way of defining headers using Annotation using retrofit Library.</p><p><strong>2. <em>Streaming data is easy</em></strong> (dividing response into chunks and processing easily)</p><p><strong>3. <em>Benefits of JetBrains Ecosystem:</em></strong> It provides feature-rich plugins to fulfill all our requirements effectively</p><h3><strong>What is Ktor Client’s Ecosystem providing:</strong></h3><ol><li>Content Negotiation and Serialization Support(e.g. XML, JSON) using Kotlin Serialization</li><li>Logging</li><li>Authentication and Authorization(e.g. Barear, JWT, OAuth)</li><li>WebSockets</li><li>Cookie &amp; Session Management</li><li>Caching and many more..</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5DCYBQzUV3OQNC-374TBJA.png" /></figure><h3><strong>Table of Contents:</strong></h3><ol><li><strong><em>Introduction to Network Call in Android</em></strong></li></ol><p><em>1.1. Using Android Library</em></p><p><em>1.2. Using Third-party Frameworks</em></p><p><strong><em>2. Create an HTTP Client(Android or OKHTTP)</em></strong></p><p><strong><em>3. Create ApiService and list all abstract functions</em></strong></p><p><strong><em>4. Create a class implementing ApiService and give an implementation of all abstract functions</em></strong></p><p><strong><em>5 . Create an instance of ApiServiceImpl.</em></strong></p><p><strong><em>6. Call the APIs of your interest (e.g Repository, ViewModel)</em></strong></p><p><strong><em>7. Conclusion</em></strong></p><h3><strong>1. Introduction to Network Call in Android</strong></h3><p>Network Calls would be performed using the Android Core Library and other third-party libraries. here I’ve taken an example of Ktor Client as a Third-party library</p><h4><strong>1.1 Using Android Core Library</strong></h4><p>Network Call is simply a URLConnection (class) created by Android to set a connection with the server using transport layer like TCP(e.g. Websockets, HTTP/HTTPS), UDP(e.g. DNS queries)</p><p>Android Library by Default provides the implementation for HTTP Connection.</p><p>To Perform an HTTP API call, android contains the HttpUrlConnection class containing all necessary details.</p><pre>suspend fun performHttpNetworkCall(url: String) {<br>  //Open HTTPConnection<br>  val connection = URL(url).openConnection() as HttpURLConnection<br><br>  connection.apply {<br>    //Set HTTPMethod Type<br>    requestMethod = &quot;GET&quot;<br><br>    //Set Headers<br>    setRequestProperty(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>    setRequestProperty(&quot;Accept&quot;, &quot;application/json&quot;)<br>    setRequestProperty(&quot;X-Api-Key&quot;, &quot;Your-API-KEY&quot;)<br><br>    connectTimeout = 1000<br>    readTimeout = 1000<br>    doInput = true<br>  }<br><br>  try {<br>    //Response Handling <br>    val inputStreamReader = InputStreamReader(connection.inputStream)<br><br>    inputStreamReader.use { reader -&gt;<br><br>      val responseString = StringBuilder()<br>      val bufferReader = BufferedReader(reader)<br><br>      bufferReader.forEachLine {<br>        responseString.append(it.trim())<br>      }<br><br>    }<br><br>  } catch (e: Exception) {<br>    //handle exception here<br><br>  } finally {<br>    //Don&#39;t forgot close the connection with server otherwise it&#39;ll leads to performance issues.<br>    connection.disconnect()<br>  }<br><br><br>}</pre><p><strong><em>1.2 Using Third-Party Library</em></strong></p><p>In this article, I’m explaining Ktor Client usage in Android covering from initial Gradle setup to API exposing to Repository/ViewModel as per your Application Architecture.</p><p>Ktor Client provides HTTPClient provides Android, OKHttp, and CIO Engine to use in the Android Ecosystem.</p><p><strong>To use Ktor Client, Add Necessary Dependency in the Gradle file of Your App Module</strong></p><pre>dependencies {<br>    ...<br>    val ktor_version = &quot;2.3.5&quot;<br><br>    //Ktor Client<br>    implementation(&quot;io.ktor:ktor-client-core:$ktor_version&quot;)<br>    //To use Android Engine<br>    implementation(&quot;io.ktor:ktor-client-android:$ktor_version&quot;)<br>    //To use OKHTTP Engine<br>    implementation(&quot;io.ktor:ktor-client-okhttp:$ktor_version&quot;)<br>    //To use Logging Feature<br>    implementation(&quot;io.ktor:ktor-client-logging:$ktor_version&quot;)<br>    implementation(&quot;ch.qos.logback:logback-classic:1.2.3&quot;)<br>    //To use Content Negotiation Feature<br>    implementation(&quot;io.ktor:ktor-client-content-negotiation:$ktor_version&quot;)<br>    //To use Content Serialization in Json Feature<br>    implementation(&quot;io.ktor:ktor-serialization-kotlinx-json:$ktor_version&quot;)<br>}</pre><h3><strong><em>2. Create an HTTP Client(Android or OKHTTP)</em></strong></h3><p>HTTP clients provide Engines and plugin configuration.</p><p>You can add only a single engine per your KtorClient. However, you can install as many different plugins with a client as you can. you can also create your custom plugin in Ktor and install this plugin with the HTTPClient as per your need.</p><pre>//OKHTTP Engine<br>val ktorOKHTTPClient = HttpClient(OkHttp) {<br>    //Engine Configuration<br>    engine {<br>        // this: OkHttpConfig<br>        config {<br>            // this: OkHttpClient.Builder<br>            followRedirects(true)<br>            //addInterceptor()<br>            //addNetworkInterceptor()<br><br>        }<br><br>    }<br><br>    <br>    //Content Negotiation Plugin<br>    install(ContentNegotiation) {<br>        json(Json {<br>            prettyPrint = true<br>            //isLenient = true<br>        })<br><br>    }<br>    //Logging Plugin<br>    install(Logging) {<br>        logger = object : io.ktor.client.plugins.logging.Logger {<br>            override fun log(message: String) {<br>                Log.v(&quot;Logger Ktor =&gt;&quot;, message)<br>            }<br><br>        }<br>        level = LogLevel.ALL<br>    }<br>    //Response Observer Plugin<br>    install(ResponseObserver) {<br>        onResponse { response -&gt;<br>            Log.d(&quot;HTTP status:&quot;, &quot;${response.status.value}&quot;)<br>        }<br>    }<br>    //Default Request Plugin to provide comman configuration(e.g. headers)<br>    install(DefaultRequest) {<br>        header(HttpHeaders.ContentType, ContentType.Application.Json)<br>    }<br>}<br><br>//Android Engine<br>val ktorAndroidClient = HttpClient(Android) {<br>    engine {<br>        connectTimeout = 1000<br>        socketTimeout = 1000<br><br>        sslManager = { httpsURLConnection -&gt;<br>            httpsURLConnection.sslSocketFactory = SslSettings.getSslContext()?.socketFactory<br>        }<br><br>    }<br><br>    install(ContentNegotiation) {<br>        json(Json {<br>            prettyPrint = true<br>            //isLenient = true<br>        })<br><br>    }<br><br>    install(Logging) {<br>        logger = object : io.ktor.client.plugins.logging.Logger {<br>            override fun log(message: String) {<br>                Log.v(&quot;Logger Ktor =&gt;&quot;, message)<br>            }<br><br>        }<br>        level = LogLevel.ALL<br>    }<br><br>    install(ResponseObserver) {<br>        onResponse { response -&gt;<br>            Log.d(&quot;HTTP status:&quot;, &quot;${response.status.value}&quot;)<br>        }<br>    }<br><br>    install(DefaultRequest) {<br>        header(HttpHeaders.ContentType, ContentType.Application.Json)<br>    }<br>}<br></pre><p>you can find out more information about another platform-specific engine(e.g. CIO, Javascript etc.) by following ktor&#39;s official website Link: <a href="https://ktor.io/docs/http-client-engines.html">https://ktor.io/docs/http-client-engines.html</a></p><p><strong><em>3. Create ApiService and list all abstract functions</em></strong></p><pre>interface ApiService {<br><br>    //Include all your api call functions signature here.<br>    suspend fun apiGetCall(query_id: String): Resource&lt;Unit&gt;<br><br>    companion object {<br>        //Static function to create object implementing ApiService<br>        fun create(client: HttpClient): ApiService {<br>            return ApiServiceImpl(client)<br>        }<br>    }<br>}</pre><p><strong><em>4. Create a class </em>implementing<em> ApiService and give an implementation of all abstract functions</em></strong></p><pre>class ApiServiceImpl(<br>    private val client: HttpClient<br>): ApiService {<br>    override suspend fun apiGetCall(query_id: String): Resource&lt;Unit&gt; {<br>        return try {<br>            //Get API Call<br>            client.get {<br>                //define url string<br>                url(https://medium.com/&quot;http://your-url-endpoint&quot;)<br>                //define query parameter with key and value<br>                parameter(&quot;id&quot;, query_id)<br>                //to pass formdata<br>                formData(FormPart(&quot;key-1&quot;, &quot;value-1&quot;, Headers.Empty), FormPart(&quot;key-2&quot;, &quot;value-2&quot;, Headers.Empty))<br><br><br>            }<br>            <br>            Resource.Success(Unit)<br>        } catch (e: Exception) {<br>            Resource.Error(e.message?: &quot;&quot;)<br>        }<br>    }<br><br>}</pre><p>Here I&#39;ve shown the <em>Get Method</em>, other methods(Post, Put, Delete) are also used in the same manner.</p><p><strong><em>5 . Create an instance of ApiServiceImpl</em></strong></p><p>You can provide a single instance of ApiService using the Dependency Injection method or directly use it by manually creating an instance every time it is needed.</p><p>I’m using the Koin DI framework to create a single instance.</p><p>To use Koin add the below dependencies into your grade file of your app module.</p><pre>dependencies {<br>    val koin_version = &quot;3.5.0&quot;<br>    val koin_compse_version = &quot;3.5.0&quot;<br>    //Koin Di<br>    implementation(&quot;io.insert-koin:koin-androidx-compose:$koin_compse_version&quot;)<br>    testImplementation(&quot;io.insert-koin:koin-test:$koin_version&quot;)<br>    testImplementation(&quot;io.insert-koin:koin-test-junit4:$koin_version&quot;)<br>    testImplementation(&quot;io.insert-koin:koin-android-test:$koin_version&quot;)<br>}</pre><pre>val appModule = module {<br>  single&lt;ApiService&gt; { ApiService.create(ktorOKHTTPClient) }<br>}<br><br>class YourApplication: Application() {<br>    override fun onCreate() {<br>        super.onCreate()<br>        startKoin {<br>            androidLogger()<br>            androidContext(this@YourApplication)<br>            modules(appModule)<br>        }<br>    }<br>}</pre><p><strong><em>6. Call the APIs of your interest (e.g Repository, ViewModel)</em></strong></p><p>Here I’ve taken an example of ViewModel for demonstration working. you can use this instance anywhere including Repository, UseCase or directly using in Compose LaunchedEffect/DisposalEffect Block.</p><pre>class YourViewModel(<br>    private val apiService: ApiService,<br>) : ViewModel() {<br><br>    fun performApiCall() {<br>      //Launching a coroutine on IO Dispatcher Thread<br>      viewmodelscope.launch(Dispatchers.IO) {<br>         //performed api-call and stored response in result variable<br>        val result = apiService.apiGetCall(&quot;query-parameter-value&quot;)<br>      }<br>    }<br>}</pre><p><strong><em>7. Conclusion</em></strong></p><p>Ktor-Client is fulfilling the needs of modern developers to work with different platforms with different engines but with the same concept and implementation. Ktor Ecosystem provides all the technological development tools that developers looking for. one of the disadvantages is that the community support is limited who are using the Ktor-Client and is growing as Kotlin MultiPlateform developers are growing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23b5803d15b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singleton Injection Without Dagger]]></title>
            <link>https://medium.com/@kevalkanpariya5051/singleton-injection-without-dagger-675ce31bda2?source=rss-2ca056449a1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/675ce31bda2</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[dagger-hilt]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Keval Kanpariya]]></dc:creator>
            <pubDate>Sat, 02 Sep 2023 11:47:49 GMT</pubDate>
            <atom:updated>2023-09-02T11:50:37.417Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong>: As we all Developers know when we use dagger hilt for dependency injection on Android projects to provide singleton objects it&#39;s a tedious task with a reasonable amount of time for compilation and generation of dependency classes. and for small-scale noncomplex processes, it’s executing unnecessarily. so in this story, we’ll talk about optimizing build performance using manual dependency injection instead of dagger-hilt.</p><p>first, create an interface AppModule and define required singleton objects as dependencies in the Interface and implement it by class.</p><pre>interface AppModule {<br>    val authApi: AuthApi<br>    val repository1: Repository1,<br>    val repository2: Repository2,<br>    val repository3: Repository3<br>}<br><br>class AppModuleImpl(<br>    private val appContext: Context<br>): AppModule {<br>    override val authApi: AuthApi by lazy {<br>        Retrofit.Builder()<br>            .baseUrl(&quot;https://your-base-url.com&quot;)<br>            .addConverterFactory(GsonConverterFactory.create())<br>            .build()<br>            .create()<br>    }<br>    override val repository1: Repository1 by lazy {<br>        Repository1Impl(authApi)<br>    }<br>    override val repository2: Repository2 by lazy {<br>        Repository2Impl(authApi)<br>    }<br>    override val repository3: Repository3 by lazy {<br>        Repository3Impl(authApi)<br>    }<br>}</pre><p>Defining Availability of App Module to Application-wide Context.</p><p>we can also define as per our specification for other Android components like service, activity, broadcast …</p><pre>class MyApp: Application() {<br><br>    companion object {<br>        lateinit var appModule: AppModule<br>    }<br><br>    override fun onCreate() {<br>        super.onCreate()<br>        appModule = AppModuleImpl(this)<br>    }<br>}</pre><pre>class MainViewModel(<br>    private val repository1: Repository1,<br>    private val repository2: Repository2,<br>    private val repository3: Repository3<br>): ViewModel() {<br><br>    fun loginRepository1() {<br>        viewModelScope.launch {<br>            repository1.login(&quot;test@test.com&quot;, &quot;test123&quot;)<br>        }<br>    }<br><br>    fun loginRepository2() {<br>        viewModelScope.launch {<br>            repository2.login(&quot;test@test.com&quot;, &quot;test123&quot;)<br>        }<br>    }<br><br>    fun loginRepository3() {<br>        viewModelScope.launch {<br>            repository3.login(&quot;test@test.com&quot;, &quot;test123&quot;)<br>        }<br>    }<br>}</pre><p>ViewModel Injection Using ViewModelFactory in Activity or Composable function-level Scope.</p><pre>fun &lt;VM: ViewModel&gt; viewModelFactory(initializer: () -&gt; VM): ViewModelProvider.Factory {<br>    return object : ViewModelProvider.Factory {<br>        override fun &lt;T : ViewModel&gt; create(modelClass: Class&lt;T&gt;): T {<br>            return initializer() as T<br>        }<br>    }<br>}</pre><pre>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            ManualDependencyInjectionTheme {<br>                val viewModel = viewModel&lt;MainViewModel&gt;(<br>                    factory = viewModelFactory {<br>                        MainViewModel(<br>                           MyApp.appModule.repositpory1,<br>                           MyApp.appModule.repositpory2,<br>                           MyApp.appModule.repositpory3<br>                        )<br>                    }<br>                )<br>                Button(onClick = {<br>                    viewModel.loginRepository1()<br>                }) {<br>                    Text(text = &quot;Login&quot;)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><strong>Reference: </strong><a href="https://youtu.be/eX-y0IEHJjM?si=UIqjwEuS0PiQYHfK">https://youtu.be/eX-y0IEHJjM?si=UIqjwEuS0PiQYHfK</a> <strong>(Philip Lackner)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=675ce31bda2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working of Handler, MessageQueue, and HandlerThread]]></title>
            <link>https://medium.com/@kevalkanpariya5051/working-of-handler-messagequeue-and-handlerthread-4f2082675986?source=rss-2ca056449a1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f2082675986</guid>
            <category><![CDATA[handler]]></category>
            <category><![CDATA[compose-ui]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[rand]]></category>
            <dc:creator><![CDATA[Keval Kanpariya]]></dc:creator>
            <pubDate>Tue, 15 Aug 2023 16:10:31 GMT</pubDate>
            <atom:updated>2023-08-15T16:10:31.267Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction: when we are building a complex application where we use multiple background threads for specific business use cases. it&#39;s important to notify the user about whether the process has been done or not. for that, we are required to use UiThread/Mainthread. but since we know that we have only one main thread available. so to resolve this issue android has introduced Handler to update any action from background thread to UIThread.</h4><p>Why use Handler: We Use Handler when we want to notify about any action performed from Background Thread to UIThread.</p><p>Handler allows us to <strong>send and process Message and Runnable</strong> <strong>objects</strong> associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue.</p><figure><img alt="sources: https://medium.com/@ankit.sinhal/handler-in-android-d138c1f4980e" src="https://cdn-images-1.medium.com/max/875/0*MkEKiEwf2zvyALjH.png" /></figure><p><strong>How to create a Handler?</strong></p><p>for the creation of a Handler, we have to first create a handler thread. handler allows us to sendMessage and Execute Runnable Task that runs sequentially.</p><p>Creating a handler first requires to create looper</p><pre>override fun run() {<br>  looper.prepare()<br>  val handler = Handler()<br>  looper.prepare()<br>}</pre><p><strong>What is Handler Thread?</strong></p><p>handler thread is a background thread with a looper</p><p>for each handler thread, it has the corresponding handler</p><p>e.g.</p><pre>//Handler Thread<br>class CustomHandlerThread: Thread() {<br><br>    lateinit var handler: CustomHandler<br>    lateinit var looper: Looper<br><br><br>    override fun run() {<br>        //creation of looper to run task of messageQueue in sequentially<br>        Looper.prepare()<br>        looper = Looper.myLooper()!!<br>        handler = CustomHandler()<br>        //initiating loop<br>        Looper.loop()<br>     <br>    }<br><br><br>}</pre><p><strong>What is Looper?</strong></p><p>looper is an infinity loop</p><p>this loop is running till we stop our handler to handle the task.</p><p><strong>What is MessageQueue?</strong></p><p>MessageQueue is a Queue in which we are putting tasks in a Queue. this Task can be of two types, 1. Message and 2. Runnable.</p><p><strong>What is Runnable?</strong></p><p>Runnable is an interface that provides a <strong><em>run</em></strong> method to execute a task. to use it we have to create a Runnable object by implementing its method. After creating it push it into MessageQueue to run a task</p><p><strong>What is Message?</strong></p><p>Message is also considered as a Task that we want to add in MessageQueue using a Handler. By using Message we are not running any block of code but simply sending arguments or Bundle data. which is handled by Handler.</p><p>e.g.: below code shows you to put runnable and messages into MessageQueue.</p><pre>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br><br>        val customHandlerThread = CustomHandlerThread()<br><br>        Log.d(&quot;MainActivity&quot;, &quot;oncreate called&quot;)<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            DemoAppTheme {<br>                Surface(<br>                    modifier = Modifier<br>                        .fillMaxSize(),<br>                    color = MaterialTheme.colorScheme.background<br>                ) {<br>                    Column {<br>                        Button(onClick = {<br>                            //starting HandlerThread<br>                            customHandlerThread.start()<br>                        }) {<br>                            Text(text = &quot;start Handler Thread&quot;)<br>                        }<br>                        Button(onClick = {<br>                            //Stop the loop<br>                            customHandlerThread.looper.quit()<br>                        }) {<br>                            Text(text = &quot;stop Handler Thread&quot;)<br>                        }<br>                        Button(onClick = {<br>                            //doing some task using Runnable<br>                            customHandlerThread.handler.post {<br>                              for (i in 1..5) {<br>                                    Log.d(&quot;MainActivity&quot;, &quot;task 1 is running: $i&quot;)<br>                                    SystemClock.sleep(1000)<br>                                }<br>                            }<br>                        }) {<br>                            Text(text = &quot;start task 1&quot;)<br>                        }<br>                        Button(onClick = {<br>                            //sending Message using sendMessage<br>                            val msg = Message.obtain()<br>                            msg.arg1 = 2<br>                            customHandlerThread.handler.sendMessage(msg)<br>                        }) {<br>                            Text(text = &quot;start task 2&quot;)<br>                        }<br>                    }<br><br>                }<br>            }<br>        }<br>    }<br><br>    <br>}</pre><p>Custom Handler to handle message</p><pre>class CustomHandler: Handler() {<br><br>    override fun handleMessage(msg: Message) {<br>        when(msg.what) {<br>            2 -&gt; {<br>                Log.d(&quot;CustomHandler&quot;, &quot;message got $2&quot;)<br>            }<br>            else -&gt; {<br>                Log.d(&quot;CustomHandler&quot;, &quot;message got ${msg.what}&quot;)<br>            }<br>        }<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f2082675986" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make an Online Learning App Using Jetpack Compose and Kotlin (Part:2)]]></title>
            <link>https://medium.com/@kevalkanpariya5051/how-to-build-online-learning-app-part-2-a3eceb3e3c72?source=rss-2ca056449a1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3eceb3e3c72</guid>
            <category><![CDATA[nas]]></category>
            <category><![CDATA[edtech]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Keval Kanpariya]]></dc:creator>
            <pubDate>Sun, 11 Jun 2023 05:24:59 GMT</pubDate>
            <atom:updated>2023-06-11T05:32:34.605Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong><em>Introduction</em></strong></h3><p>In the previous article, I discussed project setup, modular architecture, and implementation of Profile Repository.</p><p>Part- 1 : <a href="https://medium.com/@kevalkanpariya5051/how-to-build-online-learning-app-part-2-a3eceb3e3c72">https://medium.com/@kevalkanpariya5051/how-to-build-online-learning-app-part-2-a3eceb3e3c72</a></p><p>Today, I’ll discuss about Implementing Auth Feature and EduCo API using Retrofit and okHttp Client for different features of the EduCo App.</p><p>In the <strong><em>di</em></strong> package, we will implement all dependency Injection needed for any repository, API, etc. there’s an AppModule.kt file, this file defines the singleton object that’s needed throughout the app.</p><pre>package dev.kevalkanpariya.featuretesteduco.di<br><br>import android.app.Application<br>import android.content.Context.MODE_PRIVATE<br>import android.content.SharedPreferences<br>import coil.ImageLoader<br>import coil.decode.SvgDecoder<br>import dagger.Module<br>import dagger.Provides<br>import dagger.hilt.InstallIn<br>import dagger.hilt.components.SingletonComponent<br>import dev.kevalkanpariya.featuretesteduco.core.domain.use_case.GetOwnUserIdUseCase<br>import dev.kevalkanpariya.featuretesteduco.core.util.Constants<br>import okhttp3.OkHttpClient<br>import okhttp3.logging.HttpLoggingInterceptor<br>import javax.inject.Singleton<br><br>@Module<br>@InstallIn(SingletonComponent::class)<br>object AppModule {<br><br>    @Provides<br>    @Singleton<br>    fun provideSharedPref(app: Application): SharedPreferences {<br>        return app.getSharedPreferences(<br>            Constants.SHARED_PREF_NAME,<br>            MODE_PRIVATE<br>        )<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideOkHttpClient(sharedPreferences: SharedPreferences): OkHttpClient {<br>        return OkHttpClient.Builder()<br>            .addInterceptor {<br>                val token = sharedPreferences.getString(Constants.KEY_JWT_TOKEN, &quot;&quot;)<br>                val modifiedRequest = it.request().newBuilder()<br>                    .addHeader(&quot;Authorization&quot;, &quot;Bearer $token&quot;)<br>                    .build()<br>                it.proceed(modifiedRequest)<br>            }<br>            .addInterceptor(<br>                HttpLoggingInterceptor().apply {<br>                    level = HttpLoggingInterceptor.Level.BODY<br>                }<br>            )<br>            .build()<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideImageLoader(app: Application): ImageLoader {<br>        return ImageLoader.Builder(app)<br>            .crossfade(true)<br>            .components {<br>                add(SvgDecoder.Factory())<br>            }<br>            .build()<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideGetOwnUserIdUseCase(sharedPreferences: SharedPreferences): GetOwnUserIdUseCase {<br>        return GetOwnUserIdUseCase(sharedPreferences)<br>    }<br><br>}</pre><p>here we’ve defined singleton objects for shared preference, okhttpClient, image loader(to load imageUrl), and for UserId. after defining this we don’t need to initialize these objects again.</p><p>Similarly, In AuthModule, CourseModule, and Profile Module there’s implementation for APIs, repository, and use case for each module</p><h3><strong>Auth Feature</strong></h3><p>— — — — — — — — — — -</p><p>In the feature_auth/data/remote package, you’ll find AuthApi.</p><p>Define interface AuthApi.</p><p>here we used the suspend function used for fetching API data on the background thread, not on the UI thread.</p><p>Each function does ApiCall and returns BasicApiResponse&lt;T&gt; which I’ve discussed in a previous article.</p><pre>interface AuthApi {<br><br>    @POST(&quot;/api/user/create&quot;)<br>    suspend fun signUp(<br>        @Body request: CreateAccountRequest<br>    ): BasicApiResponse&lt;Unit&gt;<br><br>    @POST(&quot;/api/user/login&quot;)<br>    suspend fun signIn(<br>        @Body request: SignInRequest<br>    ): BasicApiResponse&lt;AuthResponse&gt;<br><br>    @POST(&quot;/api/user/reset_password&quot;)<br>    suspend fun resetPassword(<br>        @Body request: ResetPasswordRequest<br>    ): BasicApiResponse&lt;Unit&gt;<br><br>    @GET(&quot;/api/user/authenticate&quot;)<br>    suspend fun authenticate()<br><br>    companion object {<br>//<br>        const val BASE_URL = &quot;http://educoservernew-env.eba-m3vepcn3.us-east-1.elasticbeanstalk.com/&quot;<br>    }<br>}</pre><p>Define the AuthRepository</p><pre>interface AuthRepository {<br><br>    suspend fun signUp(<br>        email: String,<br>        username: String,<br>        password: String<br>    ): SimpleResource<br><br>    suspend fun signIn(<br>        email: String,<br>        password: String<br>    ): SimpleResource<br><br>    suspend fun resetPassword(<br>        oldPassword: String,<br>        newPassword: String<br>    ): SimpleResource<br><br>    suspend fun authenticate(): SimpleResource<br>}</pre><p>Implement AuthRepository using Dagger Hilt</p><pre>class AuthRepositoryImpl(<br>    private val api: AuthApi,<br>    private val sharedPreferences: SharedPreferences<br>) : AuthRepository {<br><br>    override suspend fun signUp(<br>        email: String,<br>        username: String,<br>        password: String<br>    ): SimpleResource {<br>        //request body to perform api call<br>        val request = CreateAccountRequest(email, username, password)<br>        return try {<br>            val response = api.signUp(request)<br>            if(response.successful) {<br>                Resource.Success(Unit)<br>            } else {<br>                response.message?.let { msg -&gt;<br>                    Resource.Error(UiText.DynamicString(msg))<br>                } ?: Resource.Error(UiText.StringResource(R.string.error_unknown))<br>            }<br>        } catch(e: IOException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.error_couldnt_reach_server)<br>            )<br>        } catch(e: HttpException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.oops_something_went_wrong)<br>            )<br>        }<br>    }<br><br>    override suspend fun signIn(email: String, password: String): SimpleResource {<br>        val request = SignInRequest(email, password)<br>        return try {<br>            val response = api.signIn(request)<br>            if(response.successful) {<br>                response.data?.let { authResponse -&gt;<br>                    println(&quot;Overriding token with ${authResponse.token}&quot;)<br>                    println(&quot;User ID ${authResponse.userId}&quot;)<br>                    //store token and userId in sharedPref after sucessfully SignIn<br>                    sharedPreferences.edit()<br>                        .putString(Constants.KEY_JWT_TOKEN, authResponse.token)<br>                        .putString(Constants.KEY_USER_ID, authResponse.userId)<br>                        .apply()<br>                }<br>                Resource.Success(Unit)<br>            } else {<br>                response.message?.let { msg -&gt;<br>                    Resource.Error(UiText.DynamicString(msg))<br>                } ?: Resource.Error(UiText.StringResource(R.string.error_unknown))<br>            }<br>        } catch(e: IOException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.error_couldnt_reach_server)<br>            )<br>        } catch(e: HttpException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.oops_something_went_wrong)<br>            )<br>        }<br>    }<br><br>    override suspend fun resetPassword(oldPassword: String, newPassword: String): SimpleResource {<br>        val request = ResetPasswordRequest(oldPassword, newPassword)<br>        return try {<br>            val response = api.resetPassword(request)<br>            //returns a boolean value for isPasswordResetSucessfully<br>            if(response.successful) {<br>                Resource.Success(Unit)<br>            } else {<br>                response.message?.let { msg -&gt;<br>                    Resource.Error(UiText.DynamicString(msg))<br>                } ?: Resource.Error(UiText.StringResource(R.string.error_unknown))<br>            }<br>        } catch(e: IOException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.error_couldnt_reach_server)<br>            )<br>        } catch(e: HttpException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.oops_something_went_wrong)<br>            )<br>        }<br>    }<br><br>    override suspend fun authenticate(): SimpleResource {<br>        return try {<br>            api.authenticate()<br>            Resource.Success(Unit)<br>        } catch(e: IOException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.error_couldnt_reach_server)<br>            )<br>        } catch(e: HttpException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.oops_something_went_wrong)<br>            )<br>        }<br>    }<br>}</pre><pre>@Module<br>@InstallIn(SingletonComponent::class)<br>object AuthModule {<br>.....<br><br> @Provides<br>    @Singleton<br>    fun provideAuthRepository(api: AuthApi, sharedPreferences: SharedPreferences): AuthRepository {<br>        return AuthRepositoryImpl(api, sharedPreferences)<br>    }<br>}</pre><p># Define Use cases for specific feature business logic.</p><blockquote>(UseCases are an extra layer between ViewModel and Repository to use Repository Function Customizable.)</blockquote><p>One of the example is here. for SignIn Feature we require validations on the username and password entered by the user. for this purpose, we’ll do validations in our use case instead of viewModel and provide more flexibility to change the use case.</p><pre>class SignInUseCase(<br>    private val repository: AuthRepository<br>) {<br><br>    suspend operator fun invoke(email: String, password: String): SignInResult {<br>        val emailError = if(email.isBlank()) AuthError.FieldEmpty else null<br>        val passwordError = if(password.isBlank()) AuthError.FieldEmpty else null<br><br>        if(emailError != null || passwordError != null) {<br>            return SignInResult(emailError, passwordError)<br>        }<br><br>        return SignInResult(<br>            result = repository.signIn(email, password)<br>        )<br>    }<br>}</pre><p><strong>Design Splash Screen</strong></p><pre>@Composable<br>fun SplashScreen(<br>    dispatcher: CoroutineDispatcher = Dispatchers.Main,<br>    onPopBackStack: () -&gt; Unit = {},<br>    onNavigate: (String) -&gt; Unit = {},<br>    viewModel: SplashViewModel = hiltViewModel()<br>) {<br>    val scale = remember {<br>        Animatable(0f)<br>    }<br>    val overshootInterpolator = remember {<br>        OvershootInterpolator(2f)<br>    }<br>    //By using LaunchedEffect we&#39;ll restrict to perform animations only when orientation changes<br>    LaunchedEffect(key1 = true) {<br>        //launch Coroutine to perform animation task<br>        withContext(dispatcher) {<br>            scale.animateTo(<br>                targetValue = 0.5f,<br>                animationSpec = tween(<br>                    durationMillis = 500,<br>                    easing = {<br>                        overshootInterpolator.getInterpolation(it)<br>                    }<br>                )<br>            )<br>        }<br>    }<br>    LaunchedEffect(key1 = true) {<br>      // Collecting EventFlow from viewmodel and perform action accordignly<br>        viewModel.eventFlow.collectLatest { event -&gt;<br>            when(event) {<br>                is UiEvent.Navigate -&gt; {<br>                    onPopBackStack()<br>                    onNavigate(event.route)<br>                }<br>                else -&gt; Unit<br>            }<br>        }<br>    }<br>    Box(<br>        modifier = Modifier.fillMaxSize(),<br>        contentAlignment = Alignment.Center<br>    ) {<br>        Image(<br>            painter = painterResource(id = R.drawable.educo_logo),<br>            contentDescription = &quot;Logo&quot;,<br>            modifier = Modifier.scale(scale.value)<br>        )<br>    }<br>}</pre><p><strong>SplashViewModel</strong></p><pre>@HiltViewModel<br>class SplashViewModel @Inject constructor(<br>    private val authenticateUseCase: AuthenticateUseCase<br>) : ViewModel() {<br><br>    private val _eventFlow = MutableSharedFlow&lt;UiEvent&gt;()<br>    val eventFlow = _eventFlow.asSharedFlow()<br><br>    init {<br>        viewModelScope.launch {<br>            when(authenticateUseCase()) {<br>                is Resource.Success -&gt; {<br>                    _eventFlow.emit(<br>                      //if user is already authenticated then user get redirect  to HomeScreen                        <br>                        UiEvent.Navigate(Screen.HomeScreen.route)<br>                    )<br>                }<br>                is Resource.Error -&gt; {<br>                    _eventFlow.emit(<br>                        UiEvent.Navigate(Screen.SignInScreen.route)<br>                    )<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><strong>Design SignInScreen &amp; SignUpScreen</strong></p><pre>@Composable<br>fun SignInScreen(<br>    scaffoldState: ScaffoldState,<br>    onNavigate: (String) -&gt; Unit = {},<br>    onSignIn: () -&gt; Unit = {},<br>    viewModel: SignInViewModel = hiltViewModel()<br>) {<br>    val emailState = viewModel.emailState.value<br>    val passwordState = viewModel.passwordState.value<br>    val state = viewModel.signInState.value<br>    val context = LocalContext.current<br><br>    LaunchedEffect(key1 = true) {<br>        viewModel.eventFlow.collectLatest { event -&gt;<br>            when (event) {<br>                is UiEvent.ShowSnackBar -&gt; {<br>                    scaffoldState.snackbarHostState.showSnackbar(<br>                        message = event.uiText.asString(context)<br>                    )<br>                }<br>                is UiEvent.Navigate -&gt; {<br>                    onNavigate(event.route)<br>                }<br>                is UiEvent.OnSignIn -&gt; {<br>                    onSignIn()<br>                }<br>                else -&gt; Unit<br>            }<br>        }<br>    }<br>    Box(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .padding(<br>                start = SpaceLarge,<br>                end = SpaceLarge,<br>                top = SpaceLarge,<br>                bottom = 50.dp<br>            )<br>    ) {<br>        Column(<br>            verticalArrangement = Arrangement.Center,<br>            modifier = Modifier<br>                .fillMaxSize()<br>                .align(Alignment.Center),<br>        ) {<br>            Text(<br>                text = stringResource(id = string.login),<br>                style = MaterialTheme.typography.h2<br>            )<br>            Spacer(modifier = Modifier.height(SpaceMedium))<br>            StandardTextField(<br>                text = emailState.text,<br>                onValueChange = {<br>                    viewModel.onEvent(SignInEvent.EnteredEmail(it))<br>                },<br>                keyboardType = KeyboardType.Email,<br>                error = when (emailState.error) {<br>                    is AuthError.FieldEmpty -&gt; stringResource(id = string.error_field_empty)<br>                    else -&gt; &quot;&quot;<br>                },<br>                hint = stringResource(id = string.login_hint)<br>            )<br>            Spacer(modifier = Modifier.height(SpaceMedium))<br>            StandardTextField(<br>                text = passwordState.text,<br>                onValueChange = {<br>                    viewModel.onEvent(SignInEvent.EnteredPassword(it))<br>                },<br>                hint = stringResource(id = string.password_hint),<br>                keyboardType = KeyboardType.Password,<br>                error = when (passwordState.error) {<br>                    is AuthError.FieldEmpty -&gt; stringResource(id = string.error_field_empty)<br>                    else -&gt; &quot;&quot;<br>                },<br>                isPasswordVisible = state.isPasswordVisible,<br>                onPasswordToggleClick = {<br>                    viewModel.onEvent(SignInEvent.TogglePasswordVisibility)<br>                }<br>            )<br>            Spacer(modifier = Modifier.height(SpaceMedium))<br>            Button(<br>                onClick = {<br>                    viewModel.onEvent(SignInEvent.SignIn)<br>                },<br>                modifier = Modifier<br>                    .align(Alignment.End)<br>            ) {<br>                Text(<br>                    text = stringResource(id = string.login),<br>                    color = MaterialTheme.colors.onPrimary<br>                )<br>            }<br>            if (state.isLoading) {<br>                CircularProgressIndicator(modifier = Modifier.align(CenterHorizontally))<br>            }<br>        }<br>        Text(<br>            text = buildAnnotatedString {<br>                append(stringResource(id = string.dont_have_an_account_yet))<br>                append(&quot; &quot;)<br>                val signUpText = stringResource(id = string.sign_up)<br>                withStyle(<br>                    style = SpanStyle(<br>                        color = MaterialTheme.colors.primary<br>                    )<br>                ) {<br>                    append(signUpText)<br>                }<br>            },<br>            style = MaterialTheme.typography.body1,<br>            modifier = Modifier<br>                .align(Alignment.BottomCenter)<br>                .clickable {<br>                    onNavigate(<br>                        Screen.SignUpScreen.route<br>                    )<br>                }<br>        )<br>    }<br><br>}<br><br><br><br>@OptIn(ExperimentalComposeUiApi::class)<br>@Composable<br>fun SignUpScreen(<br>    scaffoldState: ScaffoldState,<br>    onPopBackStack: () -&gt; Unit,<br>    viewModel: SignUpViewModel = hiltViewModel()<br>) {<br>    val usernameState = viewModel.usernameState.value<br>    val emailState = viewModel.emailState.value<br>    val passwordState = viewModel.passwordState.value<br>    val registerState = viewModel.registerState.value<br>    val context = LocalContext.current<br><br>//to get current keyboard state<br>    val keyboardController = LocalSoftwareKeyboardController.current<br><br>    LaunchedEffect(key1 = true) {<br>        viewModel.onRegister.collect {<br>            onPopBackStack()<br>        }<br>    }<br>    LaunchedEffect(key1 = keyboardController) {<br>        viewModel.eventFlow.collectLatest { event -&gt;<br>            when(event) {<br>                is UiEvent.ShowSnackBar -&gt; {<br>                    keyboardController?.hide()<br>                    scaffoldState.snackbarHostState.showSnackbar(<br>                        event.uiText.asString(context),<br>                        duration = SnackbarDuration.Long<br>                    )<br>                }<br>                else -&gt; Unit<br>            }<br>        }<br>    }<br><br>    Box(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .padding(<br>                start = SpaceLarge,<br>                end = SpaceLarge,<br>                top = SpaceLarge,<br>                bottom = 50.dp<br>            )<br>    ) {<br>        Column(<br>            verticalArrangement = Arrangement.Center,<br>            modifier = Modifier<br>                .fillMaxSize()<br>                .align(Alignment.Center),<br>        ) {<br>            Text(<br>                text = stringResource(id = R.string.signup),<br>                style = MaterialTheme.typography.h2<br>            )<br>            Spacer(modifier = Modifier.height(SpaceMedium))<br>            StandardTextField(<br>                text = emailState.text,<br>                onValueChange = {<br>                    viewModel.onEvent(SignUpEvent.EnteredEmail(it))<br>                },<br>                error = when (emailState.error) {<br>                    is AuthError.FieldEmpty -&gt; {<br>                        stringResource(id = R.string.error_field_empty)<br>                    }<br>                    is AuthError.InvalidEmail -&gt; {<br>                        stringResource(id = R.string.not_a_valid_email)<br>                    }<br>                    else -&gt; &quot;&quot;<br>                },<br>                keyboardType = KeyboardType.Email,<br>                hint = stringResource(id = R.string.email)<br>            )<br>            Spacer(modifier = Modifier.height(SpaceMedium))<br>            StandardTextField(<br>                text = usernameState.text,<br>                onValueChange = {<br>                    viewModel.onEvent(SignUpEvent.EnteredUsername(it))<br>                },<br>                error = when (viewModel.usernameState.value.error) {<br>                    is AuthError.FieldEmpty -&gt; {<br>                        stringResource(id = R.string.error_field_empty)<br>                    }<br>                    is AuthError.InputTooShort -&gt; {<br>                        stringResource(id = R.string.input_too_short, Constants.MIN_USERNAME_LENGTH)<br>                    }<br>                    else -&gt; &quot;&quot;<br>                },<br>                hint = stringResource(id = R.string.username)<br>            )<br>            Spacer(modifier = Modifier.height(SpaceMedium))<br>            StandardTextField(<br>                text = passwordState.text,<br>                onValueChange = {<br>                    viewModel.onEvent(SignUpEvent.EnteredPassword(it))<br>                },<br>                hint = stringResource(id = R.string.password_hint),<br>                keyboardType = KeyboardType.Password,<br>                error = when (passwordState.error) {<br>                    is AuthError.FieldEmpty -&gt; {<br>                        stringResource(id = R.string.error_field_empty)<br>                    }<br>                    is AuthError.InputTooShort -&gt; {<br>                        stringResource(id = R.string.input_too_short, Constants.MIN_PASSWORD_LENGTH)<br>                    }<br>                    is AuthError.InvalidPassword -&gt; {<br>                        stringResource(id = R.string.invalid_password)<br>                    }<br>                    else -&gt; &quot;&quot;<br>                },<br>                isPasswordVisible = passwordState.isPasswordVisible,<br>                onPasswordToggleClick = {<br>                    viewModel.onEvent(SignUpEvent.TogglePasswordVisibility)<br>                }<br>            )<br>            Spacer(modifier = Modifier.height(SpaceMedium))<br>            Button(<br>                onClick = {<br>                    viewModel.onEvent(SignUpEvent.SignUp)<br>                },<br>                enabled = !registerState.isLoading,<br>                modifier = Modifier<br>                    .align(Alignment.End)<br>            ) {<br>                Text(<br>                    text = stringResource(id = R.string.signup),<br>                    color = MaterialTheme.colors.onPrimary<br>                )<br>            }<br>            if(registerState.isLoading) {<br>                CircularProgressIndicator(<br>                    modifier = Modifier.align(CenterHorizontally)<br>                )<br>            }<br>        }<br>        Text(<br>            text = buildAnnotatedString {<br>                append(stringResource(id = R.string.already_have_an_account))<br>                append(&quot; &quot;)<br>                val signUpText = stringResource(id = R.string.sign_in)<br>                withStyle(<br>                    style = SpanStyle(<br>                        color = MaterialTheme.colors.primary<br>                    )<br>                ) {<br>                    append(signUpText)<br>                }<br>            },<br>            style = MaterialTheme.typography.body1,<br>            modifier = Modifier<br>                .align(Alignment.BottomCenter)<br>                .clickable {<br>                    onPopBackStack()<br>                }<br>        )<br>    }<br><br>}</pre><p><strong>SignInEvent &amp; SignUpEvent</strong></p><pre>sealed class SignInEvent {<br><br>    data class EnteredEmail(val email: String): SignInEvent()<br>    data class EnteredPassword(val password: String): SignInEvent()<br>    object SignIn: SignInEvent()<br>    object TogglePasswordVisibility: SignInEvent()<br>}<br><br>sealed class SignUpEvent {<br>    data class EnteredUsername(val value: String): SignUpEvent()<br>    data class EnteredEmail(val value: String): SignUpEvent()<br>    data class EnteredPassword(val value: String): SignUpEvent()<br>    object TogglePasswordVisibility : SignUpEvent()<br>    object SignUp : SignUpEvent()<br>}</pre><p><strong>SignIn &amp; SignUp State</strong></p><pre>data class SignInState(<br>    val isLoading: Boolean = false,<br>    val isPasswordVisible: Boolean = false<br>)<br>data class RegisterState(<br>    val isLoading: Boolean = false<br>)</pre><p><strong>SignIn &amp; SignUp ViewModel</strong></p><pre>@HiltViewModel<br>class SignInViewModel @Inject constructor(<br>    private val signInUseCase: SignInUseCase<br>) : ViewModel() {<br><br>    // Ui States for Email, Password and SignIn<br>    private val _emailState = mutableStateOf(StandardTextFieldState())<br>    val emailState: State&lt;StandardTextFieldState&gt; = _emailState<br><br>    private val _passwordState = mutableStateOf(StandardTextFieldState())<br>    val passwordState: State&lt;StandardTextFieldState&gt; = _passwordState<br><br>    private val _signInState = mutableStateOf(SignInState())<br>    val signInState: State&lt;SignInState&gt; = _signInState<br><br>    private val _eventFlow = MutableSharedFlow&lt;UiEvent&gt;()<br>    val eventFlow = _eventFlow.asSharedFlow()<br><br>    fun onEvent(event: SignInEvent) {<br>        when(event) {<br>            is SignInEvent.EnteredEmail -&gt; {<br>                _emailState.value = emailState.value.copy(<br>                    text = event.email<br>                )<br>            }<br>            is SignInEvent.EnteredPassword -&gt; {<br>                _passwordState.value = passwordState.value.copy(<br>                    text = event.password<br>                )<br>            }<br>            is SignInEvent.TogglePasswordVisibility -&gt; {<br>                _signInState.value = signInState.value.copy(<br>                    isPasswordVisible = !signInState.value.isPasswordVisible<br>                )<br>            }<br>            is SignInEvent.SignIn -&gt; {<br>// perform suspend function call in coroutinescope <br>                viewModelScope.launch {<br>                    _signInState.value = signInState.value.copy(isLoading = true)<br>                    val signInResult = signInUseCase(<br>                        email = emailState.value.text,<br>                        password = passwordState.value.text<br>                    )<br><br>                    _signInState.value = signInState.value.copy(isLoading = false)<br>                    if(signInResult.emailError != null) {<br>                        _emailState.value = emailState.value.copy(<br>                            error = signInResult.emailError<br>                        )<br>                    }<br>                    if(signInResult.passwordError != null) {<br>                        _passwordState.value = _passwordState.value.copy(<br>                            error = signInResult.passwordError<br>                        )<br>                    }<br>                    when(signInResult.result) {<br>                        is Resource.Success -&gt; {<br>                            _eventFlow.emit(UiEvent.OnSignIn)<br>                        }<br>                        is Resource.Error -&gt; {<br>                            _eventFlow.emit(<br>                                UiEvent.ShowSnackBar(<br>                                    signInResult.result.uiText ?: UiText.unknownError()<br>                                )<br>                            )<br>                        }<br><br>                        else -&gt; {}<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}<br><br>@HiltViewModel<br>class SignUpViewModel @Inject constructor(<br>    private val signupUseCase: SignUpUseCase<br>) : ViewModel() {<br><br>    private val _emailState = mutableStateOf(StandardTextFieldState())<br>    val emailState: State&lt;StandardTextFieldState&gt; = _emailState<br><br>    private val _usernameState = mutableStateOf(StandardTextFieldState())<br>    val usernameState: State&lt;StandardTextFieldState&gt; = _usernameState<br><br>    private val _passwordState = mutableStateOf(PasswordTextFieldState())<br>    val passwordState: State&lt;PasswordTextFieldState&gt; = _passwordState<br><br>    private val _registerState = mutableStateOf(RegisterState())<br>    val registerState: State&lt;RegisterState&gt; = _registerState<br><br>    private val _eventFlow = MutableSharedFlow&lt;UiEvent&gt;()<br>    val eventFlow = _eventFlow.asSharedFlow()<br><br>    private val _onRegister = MutableSharedFlow&lt;Unit&gt;(replay = 1)<br>    val onRegister = _onRegister.asSharedFlow()<br><br>    fun onEvent(event: SignUpEvent) {<br>        when(event) {<br>            is SignUpEvent.EnteredUsername -&gt; {<br>                _usernameState.value = _usernameState.value.copy(<br>                    text = event.value<br>                )<br>            }<br>            is SignUpEvent.EnteredEmail -&gt; {<br>                _emailState.value = _emailState.value.copy(<br>                    text = event.value<br>                )<br>            }<br>            is SignUpEvent.EnteredPassword -&gt; {<br>                _passwordState.value = _passwordState.value.copy(<br>                    text = event.value<br>                )<br>            }<br>            is SignUpEvent.TogglePasswordVisibility -&gt; {<br>                _passwordState.value = _passwordState.value.copy(<br>                    isPasswordVisible = !passwordState.value.isPasswordVisible<br>                )<br>            }<br>            is SignUpEvent.SignUp -&gt; {<br>                signUp()<br>            }<br>        }<br>    }<br><br>    private fun signUp() {<br>        viewModelScope.launch {<br>            _usernameState.value = usernameState.value.copy(error = null)<br>            _emailState.value = emailState.value.copy(error = null)<br>            _passwordState.value = passwordState.value.copy(error = null)<br>            _registerState.value = RegisterState(isLoading = true)<br>            val signUpResult = signupUseCase(<br>                email = emailState.value.text,<br>                username = usernameState.value.text,<br>                password = passwordState.value.text<br>            )<br>            if(signUpResult.emailError != null) {<br>                _emailState.value = emailState.value.copy(<br>                    error = signUpResult.emailError<br>                )<br>            }<br>            if(signUpResult.usernameError != null) {<br>                _usernameState.value = _usernameState.value.copy(<br>                    error = signUpResult.usernameError<br>                )<br>            }<br>            if(signUpResult.passwordError != null) {<br>                _passwordState.value = _passwordState.value.copy(<br>                    error = signUpResult.passwordError<br>                )<br>            }<br>            when(signUpResult.result) {<br>                is Resource.Success -&gt; {<br>                    _eventFlow.emit(<br>                        UiEvent.ShowSnackBar(UiText.StringResource(R.string.success_registration))<br>                    )<br>                    _onRegister.emit(Unit)<br>                    _registerState.value = RegisterState(isLoading = false)<br>                    _usernameState.value = StandardTextFieldState()<br>                    _emailState.value = StandardTextFieldState()<br>                    _passwordState.value = PasswordTextFieldState()<br>                }<br>                is Resource.Error -&gt; {<br>                    _eventFlow.emit(<br>                        UiEvent.ShowSnackBar(signUpResult.result.uiText ?: UiText.unknownError())<br>                    )<br>                    _registerState.value = RegisterState(isLoading = false)<br>                }<br>                null -&gt; {<br>                    _registerState.value = RegisterState(isLoading = false)<br>                }<br>            }<br>        }<br>    }<br><br>}</pre><p>Define routes for each screen</p><pre>package dev.kevalkanpariya.featuretesteduco.core.util<br><br>sealed class Screen(val route: String) {<br><br>    //Auth<br>    object SplashScreen : Screen(&quot;splash_screen&quot;)<br>    object SignInScreen : Screen(&quot;login_screen&quot;)<br>    object SignUpScreen : Screen(&quot;register_screen&quot;)<br><br>...<br>}</pre><p>define NavHost for Navigation Graph with start destination Splash Route</p><pre>package dev.kevalkanpariya.featuretesteduco.core.presentation.components<br><br>@OptIn(ExperimentalCoilApi::class)<br>@Composable<br>fun Navigation(<br>    imageLoader: ImageLoader,<br>    navController: NavHostController,<br>    scaffoldState: ScaffoldState,<br>) {<br>    NavHost(<br>        navController = navController,<br>        startDestination = Screen.SignInScreen.route,<br>        modifier = Modifier.fillMaxSize()<br>    ) {<br><br>        composable(Screen.SplashScreen.route) {<br>            SplashScreen(<br>                onPopBackStack = navController::popBackStack,<br>                onNavigate = navController::navigate<br>            )<br>        }<br><br>        composable(Screen.SignInScreen.route) {<br>            SignInScreen(<br>                onNavigate = navController::navigate,<br>                onSignIn = {<br>                    navController.popBackStack(<br>                        route = Screen.SignInScreen.route,<br>                        inclusive = true<br>                    )<br>                    navController.navigate(route = Screen.HomeScreen.route)<br>                },<br>                scaffoldState = scaffoldState<br>            )<br>        }<br><br>        composable(Screen.SignUpScreen.route) {<br>            SignUpScreen(<br>                scaffoldState = scaffoldState,<br>                onPopBackStack = navController::popBackStack<br>            )<br>        }<br>.....<br>}</pre><p>Add NavHost to MainActivity</p><pre>@AndroidEntryPoint<br>class MainActivity : ComponentActivity() {<br><br>    @Inject<br>    lateinit var imageLoader: ImageLoader<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            window.statusBarColor = MaterialTheme.colors.background.toArgb()<br><br>            FeatureTestEduCoTheme {<br>                Surface(<br>                    modifier = Modifier.fillMaxSize(),<br>                    color = MaterialTheme.colors.background<br>                ) {<br>                    val navController = rememberNavController()<br>                    val navBackStackEntry by navController.currentBackStackEntryAsState()<br>                    val scaffoldState = rememberScaffoldState()<br>                    StandardScaffold(<br>                        navController = navController,<br>                        state = scaffoldState,<br>                        modifier = Modifier.fillMaxSize()<br>                    ) {<br>                        Navigation( imageLoader, navController, scaffoldState)<br>                    }<br><br>                }<br>            }<br>        }<br>    }</pre><p>before the running application make sure you create an application for Hilt and add into Manifest File</p><pre>package dev.kevalkanpariya.featuretesteduco<br><br>import android.app.Application<br>import dagger.hilt.android.HiltAndroidApp<br><br>@HiltAndroidApp<br>class EduCoApplication : Application()</pre><pre>&lt;application<br>        ...<br>        android:name=&quot;.EduCoApplication&quot;<br>        android:usesCleartextTraffic=&quot;true&quot; <br>        ...<br>&gt;<br>        <br>&lt;/application&gt;</pre><p><strong><em>find the entire source code below..</em></strong></p><p><a href="https://github.com/keval-kanp-1011/EduCo">GitHub - keval-kanp-1011/EduCo: Online Learning Plateform through Courses</a></p><p><em>*Source: Philip Lackner : </em><a href="https://github.com/philipplackner"><em>https://github.com/philipplackner</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3eceb3e3c72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make an Online Learning App Using Jetpack Compose and Kotlin (Part : 1)]]></title>
            <link>https://medium.com/@kevalkanpariya5051/make-an-online-learning-app-using-jetpack-compose-and-kotlin-part-1-8084a95bed91?source=rss-2ca056449a1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8084a95bed91</guid>
            <dc:creator><![CDATA[Keval Kanpariya]]></dc:creator>
            <pubDate>Wed, 31 May 2023 06:39:18 GMT</pubDate>
            <atom:updated>2023-05-31T10:16:31.205Z</atom:updated>
            <content:encoded><![CDATA[<h3>Make an Online Learning App Using Jetpack Compose and Kotlin (Part: 1)</h3><h3><strong>Introduction</strong></h3><p>In this article, I will cover How to make an ed-tech app using the emerging modern Android framework Jetpack compose.</p><h3><strong>Proceeding</strong></h3><p>Add the following Plugins in the build.gradle file(Project Module)</p><pre>plugins {<br>    ..<br>    id &#39;org.jetbrains.kotlin.android&#39; version &#39;1.8.10&#39; apply false<br>    id &quot;org.jetbrains.kotlin.plugin.serialization&quot; version &quot;1.8.10&quot; apply false<br>    id &#39;com.google.dagger.hilt.android&#39; version &#39;2.44&#39; apply false<br>}</pre><p>setup the build.gradle file(App Module) as mentioned below.</p><pre>plugins {<br>    id &#39;com.android.application&#39;<br>    id &#39;org.jetbrains.kotlin.android&#39;<br>    id &#39;kotlin-kapt&#39;<br>    id &#39;dagger.hilt.android.plugin&#39;<br>    id &#39;kotlinx-serialization&#39;<br>    id &#39;kotlin-parcelize&#39;<br>}<br><br>android {<br>..<br><br>    compileOptions {<br>            sourceCompatibility JavaVersion.VERSION_17<br>            targetCompatibility JavaVersion.VERSION_17<br>    }<br>    kotlinOptions {<br>        jvmTarget = 17<br>    }<br>    composeOptions {<br>        kotlinCompilerExtensionVersion &#39;1.4.3&#39;<br>    }<br>}<br><br>dependencies {<br>..<br><br>//AndroidX<br><br>    // Coroutine Lifecycle Scopes<br>    implementation &quot;androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1&quot;<br>    implementation &quot;androidx.lifecycle:lifecycle-runtime-ktx:2.3.1&quot;<br>    implementation &quot;androidx.lifecycle:lifecycle-viewmodel-compose:2.6.0&quot;<br>    implementation &quot;androidx.lifecycle:lifecycle-runtime-compose:2.6.0&quot;<br><br>    // DataStore Preferences<br>    implementation &quot;androidx.datastore:datastore-preferences:1.0.0&quot;<br>    // Compose Navigation<br>    implementation &quot;androidx.navigation:navigation-compose:2.5.3&quot;<br>    // Compose Paging<br>    implementation &#39;androidx.paging:paging-compose:1.0.0-alpha12&#39;<br>    // Compose Constraint Layout<br>    implementation &quot;androidx.constraintlayout:constraintlayout-compose:1.0.1&quot;<br><br><br>    //Jetbrains<br><br>    // Kotlinx Serialization<br>    implementation &quot;org.jetbrains.kotlinx:kotlinx-serialization-json:1.4.1&quot;<br>    // Coroutines<br>    implementation &#39;org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.1&#39;<br>    implementation &#39;org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.1&#39;<br><br><br><br><br>    //Dagger-Hilt<br>    implementation &#39;com.google.dagger:hilt-android:2.44&#39;<br>    kapt &#39;com.google.dagger:hilt-compiler:2.44&#39;<br>    implementation &#39;androidx.hilt:hilt-navigation-compose:1.0.0&#39;<br><br>    // Coil - Compose<br>    implementation &quot;io.coil-kt:coil-compose:2.2.2&quot;<br>    implementation &quot;io.coil-kt:coil-svg:2.2.2&quot;<br><br>    // UCrop<br>    implementation &#39;com.github.yalantis:ucrop:2.2.6&#39;<br><br>    //Accompanist<br><br>    // Horizontal Pager and Indicators<br>    implementation &quot;com.google.accompanist:accompanist-pager:0.24.3-alpha&quot;<br>    implementation &quot;com.google.accompanist:accompanist-pager-indicators:0.24.3-alpha&quot;<br>    // Swipe to Refresh<br>    implementation &quot;com.google.accompanist:accompanist-swiperefresh:0.24.3-alpha&quot;<br>    // System UI Controller<br>    implementation &quot;com.google.accompanist:accompanist-systemuicontroller:0.24.3-alpha&quot;<br>    // Flow Layout<br>    implementation &quot;com.google.accompanist:accompanist-flowlayout:0.24.3-alpha&quot;<br><br>    // Palette API<br>    implementation &quot;androidx.palette:palette-ktx:1.0.0&quot;<br><br>    // Retrofit<br>    implementation &#39;com.squareup.retrofit2:retrofit:2.9.0&#39;<br>    implementation(&quot;com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0&quot;)<br><br>    //OKHttp<br>    implementation &quot;com.squareup.okhttp3:okhttp:5.0.0-alpha.2&quot;<br>    implementation &quot;com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.2&quot;<br>    implementation(&quot;com.squareup.okhttp3:okhttp-urlconnection:4.4.1&quot;)<br><br>    // Exoplayer<br>    implementation &#39;androidx.media3:media3-exoplayer:1.0.0&#39;<br>    implementation &#39;androidx.media3:media3-ui:1.0.0&#39;<br><br>    // Timber for Logging<br>    implementation &#39;com.jakewharton.timber:timber:4.7.1&#39;<br>}</pre><p><strong><em>Modular Architecture</em></strong> in dev.kevalkanpariya.featuretesteduco Package</p><pre> .<br>    ├── ...<br>    ├── core                    <br>    │   ├── data<br>    │   │   ├── dto/response<br>    │   │   └── repository          <br>    │   ├── domain<br>    │   │   ├── models<br>    │   │   ├── repository<br>    │   │   ├── states<br>    │   │   ├── use_case<br>    │   │   └── util              <br>    │   ├── presentation <br>    │   │   ├── components<br>    │   │   └── util            <br>    │   └── util            <br>    │                         <br>    ├── di                    <br>    ├── feature_auth<br>    │   ├── data<br>    │   │   ├── remote<br>    │   │   └── repository<br>    │   ├── domain<br>    │   │   ├── models<br>    │   │   ├── repository<br>    │   │   └── use_case<br>    │   └── presentation<br>    │   │   ├── sign_in<br>    │   │   ├── sign_up<br>    │   │   ├── splash<br>    │   │   └── util<br>    ├── feature_course<br>    │   ├── data<br>    │   ├── domain<br>    │   └── presentation <br>    ├── feature_profile<br>    │   ├── data<br>    │   ├── domain<br>    │   └── presentation<br>    ├── feature_settings<br>    │   ├── data<br>    │   ├── domain<br>    │   └── presentation<br>    └── ui/theme</pre><p>Declare Common Model data classes for ApiResponse</p><pre>package dev.kevalkanpariya.featuretesteduco.core.data.dto.response<br><br>import dev.kevalkanpariya.featuretesteduco.core.domain.models.CourseOverview<br><br>@kotlinx.serialization.Serializable<br>data class BasicApiResponse&lt;T&gt;(<br>    val successful: Boolean,<br>    val message: String? = null,<br>    val data: T? = null<br>)<br><br>@kotlinx.serialization.Serializable<br>data class CoursesResponse(<br>    val page: Int,<br>    val results: List&lt;CourseOverview&gt;,<br>    val totalPages: Int,<br>    val totalResults: Int<br>)</pre><pre>package dev.kevalkanpariya.featuretesteduco.core.data.dto.response<br><br>import dev.kevalkanpariya.featuretesteduco.core.domain.models.UserItem<br><br>@kotlinx.serialization.Serializable<br>data class UserItemDto(<br>    val userId: String,<br>    val username: String,<br>    val profilePictureUrl: String,<br>    val bio: String,<br>    val isFollowing: Boolean,<br>    val name: String<br>) {<br>    fun toUserItem(): UserItem {<br>        return UserItem(<br>            userId = userId,<br>            username = username,<br>            profilePictureUrl = profilePictureUrl,<br>            bio = bio,<br>            isFollowing = isFollowing,<br>            name = name<br>        )<br>    }<br>}</pre><p>Implement ProfileRepository because it is shared between most of the features</p><pre>class ProfileRepositoryImpl(<br>    private val profileApi: ProfileApi,<br>    private val sharedPreferences: SharedPreferences,<br>): ProfileRepository {<br>    override suspend fun getCoursesPaged(<br>        page: Int,<br>        pageSize: Int,<br>        userId: String<br>    ): Resource&lt;List&lt;CourseOverview&gt;&gt; {<br>        return try {<br>            val courses = profileApi.getCoursesPaged(<br>                userId = userId,<br>                page = page,<br>                pageSize = pageSize<br>            ).data<br>            Resource.Success(data = courses)<br>        } catch(e: IOException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.error_couldnt_reach_server)<br>            )<br>        } catch(e: HttpException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.oops_something_went_wrong)<br>            )<br>        }<br>    }<br><br>    override suspend fun getUserInfos(page: Int, pageSize: Int): Resource&lt;List&lt;UserItem&gt;&gt; {<br>        return try {<br>            val response = profileApi.getUserInfos(page = page, pageSize = pageSize)<br>            Resource.Success(<br>                data = response.data<br>            )<br>        } catch(e: IOException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.error_couldnt_reach_server)<br>            )<br>        } catch(e: HttpException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.oops_something_went_wrong)<br>            )<br>        }<br>    }<br><br>    override suspend fun getProfile(userId: String): Resource&lt;Profile&gt; {<br>        return try {<br>            val response = profileApi.getProfile(userId)<br>            if(response.successful) {<br>                Resource.Success(response.data)<br>            } else {<br>                response.message?.let { msg -&gt;<br>                    Resource.Error(UiText.DynamicString(msg))<br>                } ?: Resource.Error(UiText.StringResource(R.string.error_unknown))<br>            }<br>        } catch(e: IOException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.error_couldnt_reach_server)<br>            )<br>        } catch(e: HttpException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.oops_something_went_wrong)<br>            )<br>        }<br>    }<br><br>    override suspend fun getProfileHeader(userId: String): Resource&lt;ProfileHeader&gt; {<br>        return try {<br>            val response = profileApi.getProfileHeader(userId)<br>            if(response.successful) {<br>                Resource.Success(response.data)<br>            } else {<br>                response.message?.let { msg -&gt;<br>                    Resource.Error(UiText.DynamicString(msg))<br>                } ?: Resource.Error(UiText.StringResource(R.string.error_unknown))<br>            }<br>        } catch(e: IOException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.error_couldnt_reach_server)<br>            )<br>        } catch(e: HttpException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.oops_something_went_wrong)<br>            )<br>        }<br>    }<br><br>    override suspend fun updateProfile(<br>        updateProfileData: UpdateProfileData,<br>        bannerImageUri: Uri?,<br>        profilePictureUri: Uri?,<br>        context: Context<br>    ): SimpleResource {<br><br>        val profilePictureFile = Uri.fromFile(<br>            File(<br>                context.cacheDir,<br>                profilePictureUri?.let { context.contentResolver.getFileName(it) }<br>            )<br>        ).toFile()<br>        val bannerFile = Uri.fromFile(<br>            File(<br>                context.cacheDir,<br>                bannerImageUri?.let { context.contentResolver.getFileName(it) }<br>            )<br>        ).toFile()<br><br>        return try {<br>            val response = profileApi.updateProfile(<br>                bannerImageUri = bannerFile?.let {<br>                    MultipartBody.Part<br>                        .createFormData(<br>                            &quot;banner_image&quot;,<br>                            bannerFile.name,<br>                            bannerFile.asRequestBody()<br>                        )<br>                },<br>                profilePictureUri = profilePictureFile?.let {<br>                    MultipartBody.Part<br>                        .createFormData(<br>                            &quot;profile_picture&quot;,<br>                            profilePictureFile.name,<br>                            profilePictureFile.asRequestBody()<br>                        )<br>                },<br>                updateProfileData = MultipartBody.Part<br>                    .createFormData(<br>                        &quot;update_profile_data&quot;,<br>                        Json.encodeToString(updateProfileData)<br>                    )<br>            )<br>            if(response.successful) {<br>                Resource.Success(Unit)<br>            } else {<br>                response.message?.let { msg -&gt;<br>                    Resource.Error(UiText.DynamicString(msg))<br>                } ?: Resource.Error(UiText.StringResource(R.string.error_unknown))<br>            }<br>        } catch(e: IOException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.error_couldnt_reach_server)<br>            )<br>        } catch(e: HttpException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.oops_something_went_wrong)<br>            )<br>        }<br>    }<br><br>    override suspend fun searchUser(query: String): Resource&lt;List&lt;UserItem&gt;&gt; {<br>        return try {<br>            val response = profileApi.searchUser(query)<br>            Resource.Success(<br>                data = response.data<br>            )<br>        } catch(e: IOException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.error_couldnt_reach_server)<br>            )<br>        } catch(e: HttpException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.oops_something_went_wrong)<br>            )<br>        }<br>    }<br><br>    override suspend fun followUser(followedUserId: String): SimpleResource {<br>        return try {<br>            val response = profileApi.followUser(<br>                followedUserId = followedUserId<br>            )<br>            if(response.successful) {<br>                Resource.Success(Unit)<br>            } else {<br>                response.message?.let { msg -&gt;<br>                    Resource.Error(UiText.DynamicString(msg))<br>                } ?: Resource.Error(UiText.StringResource(R.string.error_unknown))<br>            }<br>        } catch(e: IOException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.error_couldnt_reach_server)<br>            )<br>        } catch(e: HttpException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.oops_something_went_wrong)<br>            )<br>        }<br>    }<br><br>    override suspend fun unfollowUser(followedUserId: String): SimpleResource {<br>        return try {<br>            val response = profileApi.unfollowUser(<br>                followedUserId = followedUserId<br>            )<br>            if(response.successful) {<br>                Resource.Success(Unit)<br>            } else {<br>                response.message?.let { msg -&gt;<br>                    Resource.Error(UiText.DynamicString(msg))<br>                } ?: Resource.Error(UiText.StringResource(R.string.error_unknown))<br>            }<br>        } catch(e: IOException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.error_couldnt_reach_server)<br>            )<br>        } catch(e: HttpException) {<br>            Resource.Error(<br>                uiText = UiText.StringResource(R.string.oops_something_went_wrong)<br>            )<br>        }<br>    }<br><br>    override fun logout() {<br>        sharedPreferences.edit()<br>            .putString(Constants.KEY_JWT_TOKEN, &quot;&quot;)<br>            .putString(Constants.KEY_USER_ID, &quot;&quot;)<br>            .apply()<br>    }<br>}</pre><p>In the constructor, we’ll provide objects of Sharedpreference and profileApi via dependency injection using the Dagger-hilt library.</p><p>Implement ProfileAPI functions getCoursesPaged, getUserInfos, getProfile, getProfileHeader, updateProfile, searchUser, followUser, unfollowUser, and logout.</p><ol><li>getCoursesPaged :— return the Resource&lt;List&lt;CourseOverview&gt;&gt;. if data from API is successfully received then we’ll show Sucess with Resource Data. otherwise Error with message and data = null.</li><li>getUserInfos, getProfile, getProfileHeader, searchUser : — same as above we have to handle API operation in the function body.</li><li>followUser and unfollowUser : — both functions return SimpleResource which is Resource&lt;Unit&gt;</li><li>updateProfile : — here we’ll create the files from URI for both bannerImageUri and ProfilePictureUri and pass it to multipart request with UpdateProfileRequest to ProfileAPI. this function gives the result as Resource&lt;Unit&gt;</li><li>logout : — return Unit. we will remove the token stored in the Shared preference by using builder pattern , first call edit(), then putString() to update data and finally call apply() to apply changes.</li></ol><p>=&gt; <strong><em>Model class for Resource. Using this class we can easily handle API errors and data to notify users directly. you can use your own customized Resource Class also</em></strong></p><pre>package dev.kevalkanpariya.featuretesteduco.core.util<br><br>typealias SimpleResource = Resource&lt;Unit&gt;<br><br>sealed class Resource&lt;T&gt;(val data: T? = null, val uiText: UiText? = null) {<br>    class Success&lt;T&gt;(data: T?): Resource&lt;T&gt;(data)<br>    class Error&lt;T&gt;(uiText: UiText, data: T? = null): Resource&lt;T&gt;(data, uiText)<br>}</pre><p><strong><em>find the entire source code below..</em></strong></p><p><a href="https://github.com/keval-kanp-1011/EduCo">https://github.com/keval-kanp-1011/EduCo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8084a95bed91" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>