<?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 Inder singh on Medium]]></title>
        <description><![CDATA[Stories by Inder singh on Medium]]></description>
        <link>https://medium.com/@singhinder640?source=rss-cf0c40c14ca4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*r1er544nvzaBqITAWRLivQ.jpeg</url>
            <title>Stories by Inder singh on Medium</title>
            <link>https://medium.com/@singhinder640?source=rss-cf0c40c14ca4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:58:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@singhinder640/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[Simplifying SDK Development with Gradle Composite Builds — A Practical Guide for Mobile Developers]]></title>
            <link>https://proandroiddev.com/simplifying-sdk-development-with-gradle-composite-builds-a-practical-guide-for-mobile-developers-78f16458399b?source=rss-cf0c40c14ca4------2</link>
            <guid isPermaLink="false">https://medium.com/p/78f16458399b</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[sdk]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Inder singh]]></dc:creator>
            <pubDate>Sun, 12 Oct 2025 07:07:20 GMT</pubDate>
            <atom:updated>2025-10-13T09:25:13.573Z</atom:updated>
            <content:encoded><![CDATA[<h3>Simplifying SDK Development with Gradle Composite Builds — A Practical Guide for Mobile Developers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*IPtJwqbnrmhXxf_WxqCMmA.jpeg" /></figure><p>If you’ve ever worked on a large-scale mobile ecosystem — think ride-hailing apps like <a href="https://medium.com/u/1f7d6a714f03">Rapido</a> — you’ve likely dealt with multiple apps (Customer, <strong>Captain (Driver App)</strong>) and a bunch of shared SDKs: <strong>Location SDK</strong>, <strong>Chat SDK</strong>, <strong>Comms SDK</strong>, etc.</p><p>As SDK developers, our daily job often looks like this:</p><ul><li>Fix a bug in the SDK</li><li>Publish it to a Maven local or GitHub package</li><li>Pull the new version into the main app (say, the Captain (Driver) App)</li><li>Rebuild, integrate, and test</li></ul><p>Sounds straightforward, right? Until you do this 10 times a day. 😅</p><p>Publishing, syncing dependencies, waiting for builds, and the biggest pain — <strong>not being able to debug SDK code directly</strong> — makes this process painfully slow.</p><p>That’s where <strong>Gradle Composite Builds</strong> come in. They can completely change the way you integrate and test SDKs locally.</p><h3>🌱 The Traditional Way (and Its Pain)</h3><p>Before composite builds, there were two common approaches:</p><h3>1. Maven Local Publication</h3><p>You’d build and publish your SDK to the local Maven repository:</p><pre>./gradlew publishToMavenLocal</pre><p>Then, in your feature module:</p><pre>implementation(&quot;com.rapido:chat-sdk:1.0.1&quot;)</pre><p>This works fine, but every small SDK change means re-publishing and syncing again. Plus, you can’t place breakpoints inside your SDK when debugging from your app.</p><h3>2.GitHub (or Remote) Publication</h3><p>You push your SDK build to a remote Maven repository (like GitHub Packages, Artifactory, or JitPack).</p><p>This helps share SDKs across teams, but it’s even slower — you need version management, credentials, and it’s not ideal for rapid iteration.</p><h3>⚡ The Modern Way — Gradle Composite Builds</h3><p>Composite builds let you include other Gradle projects (like your SDKs) directly into your main app <strong>without publishing them anywhere</strong>.</p><p>They work seamlessly across multiple modules or repositories and make debugging &amp; testing SDKs a breeze.</p><p>Here’s how you can set it up 👇</p><h3>🧩 Setting Up Composite Builds (with Kotlin DSL)</h3><p>Let’s say you have the following projects:</p><pre>root/<br> ├── apps/<br> │    └── captain-app/   ← (Driver App)<br> ├── sdks/<br> │    ├── chat-sdk/<br> │    ├── location-sdk/<br> │    └── comms-sdk/</pre><p>You want your <strong>Captain (Driver) App</strong> to use chat-sdk as a dependency — but instead of fetching it from Maven, you want to use your local source.</p><h3>Example (Setup)</h3><p>Here’s how we use composite builds internally at <a href="https://medium.com/u/1f7d6a714f03">Rapido</a> for testing SDKs locally without publishing them.</p><pre>// =============================================================================<br>// Composite Build for Local SDK Testing<br>// =============================================================================<br>// This allows testing local changes in platform-mobile-sdks without publishing<br>// Path: ../platform-mobile-sdks is relative to this project&#39;s root<br>// To disable: Comment out this entire block<br>// =============================================================================<br>includeBuild(&quot;../platform-mobile-sdks&quot;) {<br>    dependencySubstitution {<br>        // Substitute network-kmm with local network module<br>        substitute(module(&quot;com.rapido.sdk:network-kmm&quot;))<br>            .using(project(&quot;:network&quot;))<br>        <br>        // Substitute chat-kmp-sdk with local chat-kmp-sdk module<br>        substitute(module(&quot;com.rapido.sdk:chat-kmp-sdk&quot;))<br>            .using(project(&quot;:chat-kmp:chat-kmp-sdk&quot;))<br>    }<br>}</pre><p>This snippet does two key things:</p><ol><li>Includes the <strong>platform-mobile-sdks</strong> build directly.</li><li>Substitutes published dependencies (network-kmm, chat-kmp-sdk) with their <strong>local project versions</strong>.</li></ol><p>With this setup, your main app (Driver App) uses the <strong>live source</strong> of these SDKs — making it easy to test, debug, and iterate instantly.</p><h3>🧠 Why This Is a Game-Changer</h3><ol><li><strong>Instant Integration Testing: </strong>You can make SDK changes and immediately test them inside your main app — no publishing, no version bumping.</li><li><strong>True Source-Level Debugging: </strong>Set breakpoints directly inside SDK code while running the app. Android Studio will treat SDK code like part of your main project.</li><li><strong>Faster Build Cycles: </strong>Since no publishing or downloading is required, you save minutes (or hours) in a dev cycle.</li><li><strong>Cleaner Collaboration: </strong>Multiple SDK teams can work together locally without fighting over Maven versions or GitHub releases.</li><li><strong>Safer Refactoring: </strong>If you change a shared interface in the SDK, you can immediately verify its impact in the main app.</li></ol><h3>🧩 Bonus Tip: Working with Multiple SDKs</h3><p>You can composite multiple SDKs in one go:</p><pre>includeBuild(&quot;../sdks/chat-sdk&quot;)<br>includeBuild(&quot;../sdks/location-sdk&quot;)<br>includeBuild(&quot;../sdks/comms-sdk&quot;)</pre><p>Gradle will resolve all these builds together as if they were part of one big project. This setup is perfect for mobile companies, where SDKs evolve rapidly and need to stay in sync across multiple apps.</p><h3>🧮 Traditional vs Composite Build — Visual Overview</h3><p>Here’s a simple diagram comparing both approaches 👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uFLIK2SQyHwM8xcicXYRvw.png" /></figure><p>No publishing. No version bumps. Just instant integration. ⚡</p><h3>🏁 Conclusion</h3><p>Gradle Composite Builds are one of those underused gems that can massively improve your SDK development workflow.</p><p>If you’re tired of constantly publishing artifacts just to test minor changes — it’s time to give composite builds a try.</p><p>They’re fast, local, and developer-friendly — exactly what modern mobile development needs.</p><h3>🚀 TL;DR</h3><ul><li>Composite builds let you link SDK source projects directly — no need for Maven publication.</li><li>You get instant integration testing, full debugging, and faster iteration cycles.</li><li>Perfect for large-scale mobile ecosystems with multiple internal SDKs.</li></ul><p><em>Big thanks to </em><a href="https://medium.com/@avishekdas128">@avishekdas128</a> <em>for the support and for helping me try this out!</em></p><p>That’s it for now! I hope you find this helpful. If you have any questions or if something isn’t clear, feel free to leave a comment. Thanks for reading! 🙌🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78f16458399b" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/simplifying-sdk-development-with-gradle-composite-builds-a-practical-guide-for-mobile-developers-78f16458399b">Simplifying SDK Development with Gradle Composite Builds — A Practical Guide for Mobile Developers</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cloud Functions and Firestore with Multiple Databases: A Developer’s Guide]]></title>
            <link>https://medium.com/@singhinder640/cloud-functions-and-firestore-with-multiple-databases-a-developers-guide-8aa38a234e20?source=rss-cf0c40c14ca4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aa38a234e20</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[cloud-functions]]></category>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Inder singh]]></dc:creator>
            <pubDate>Sat, 19 Oct 2024 15:36:17 GMT</pubDate>
            <atom:updated>2024-10-19T15:36:17.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kx5tTRK1tmo_FH12UGbp0Q.jpeg" /><figcaption>firestore-databases and cloud functions</figcaption></figure><p>If you’ve ever dabbled in Firebase Cloud Functions and Firestore, you know how powerful these tools can be for building serverless applications. But what happens when your app starts to scale and you need to juggle multiple Firestore databases? It might sound tricky, but don’t worry — it’s completely manageable with the right approach.</p><p>In this guide, I’ll take you through the process of integrating Cloud Functions with multiple Firestore databases, highlighting the benefits, challenges, and best practices along the way.</p><p><strong>Why Use Multiple Firestore Databases?</strong></p><p>You might be wondering: why would I need more than one Firestore database? Here are a few common scenarios:</p><p>• <strong>Separation of Environments:</strong> You might want to keep your development, staging, and production environments apart to avoid any accidental mishaps.</p><p>• <strong>Data Isolation:</strong> If your app serves multiple tenants or regions, separating their data into different Firestore instances makes sense.</p><p>• <strong>Scalability:</strong> As your app grows, spreading data across multiple databases can help you dodge limits imposed by Firestore (like document reads and writes).</p><p><strong>Challenges of Working with Multiple Databases</strong></p><p>While leveraging multiple Firestore databases with Cloud Functions is a powerful strategy, it does come with its own set of challenges. Let’s break those down:</p><p>1. <strong>Connecting to the Right Instance:</strong></p><p>Each Firestore database has its own unique configuration (like projectId and credentials). You’ll need to ensure that your Cloud Function is connected to the correct database instance at all times. This requires managing separate initialization flows for each instance, which can lead to errors if you’re not careful.</p><p>2. <strong>Authentication and Security:</strong></p><p>Each Firestore database needs secure access, meaning you’ll have to handle multiple authentication flows. Whether you’re using service accounts or API keys, managing secure access for each instance is crucial. If you mishandle this, you risk unauthorized access or data leaks.</p><p>3. <strong>Sparse Documentation:</strong></p><p>One of the biggest hurdles developers face is the lack of comprehensive documentation when working with multiple Firestore instances in Cloud Functions. Most Firebase documentation focuses on using a single Firestore instance, leaving you to piece together solutions for handling multiple databases, which can be time-consuming.</p><p><strong>Setting Up an Additional Firestore Database</strong></p><p>Let’s start by creating a new Firestore database (besides the default one). Here’s how you can do it:</p><p>1. Go to <a href="https://console.cloud.google.com/">Google Cloud Console</a>.</p><p>2. <strong>In the search bar, type “Firestore”</strong> and select it from the results.</p><p>3. <strong>Click on Create Database</strong> and follow the prompts to configure your new Firestore instance. Let’s call this new database firestore-db-2.</p><p>Once you create it, you’ll have a secondary Firestore instance (firestore-db-2) that can work alongside your default database. In the next sections, I’ll show you how to configure Cloud Functions to connect to this new database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RGvMwriDe0TAPCJSUQL2ag.png" /></figure><p><strong>Connecting Cloud Functions to Your New Firestore Database</strong></p><p>Now that you have your new Firestore database (firestore-db-2) set up, let’s create a Cloud Function and connect it to this database. Here’s how:</p><p>1. <strong>Create the Cloud Function</strong></p><p>Head back to the <a href="https://console.cloud.google.com/">Google Cloud Console</a> dashboard and search for <strong>Cloud Functions</strong>. Once there, click <strong>Create Function</strong>. You’ll be prompted to enter details such as the function name, runtime, and trigger type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1c5E2zVhy_D3T17A52vlPw.png" /></figure><p>2. <strong>Configure the New Database Instance</strong></p><p>In the Cloud Function setup, you’ll need to configure your function to connect to firestore-db-2. This involves initializing Firebase Admin SDK with the correct credentials, just as we did earlier when creating the Firestore instance.</p><p>3. <strong>Service Account and Permissions</strong></p><p>To enable your Cloud Function to read from and write to Firestore, you’ll need a <strong>service account</strong>. Ensure that this service account has the necessary permissions to interact with Firestore, including <strong>Firestore User</strong> or <strong>Firestore Admin</strong> roles. Without proper permissions, your Cloud Function will fail to access the database.</p><p>4. <strong>Choose the Trigger Type</strong></p><p>Google Cloud Functions offers various triggers depending on your use case. You can trigger your function on new document creation, updates, deletions, or even periodically using a scheduler. Select the trigger type that suits your workflow. For example, if you want to perform actions when a new document is added to firestore-db-2, you can set up a Firestore trigger for document creation.</p><p>5. <strong>Optimize for Region and Latency</strong></p><p>When deploying both Firebase and Cloud Functions, it’s critical to ensure they’re in the <strong>same region</strong>. This minimizes latency and reduces the cost associated with inter-region communication. For instance, if your Firestore database is located in us-central1, make sure your Cloud Function is deployed in the same region to avoid unnecessary delays and communication costs.</p><p>6. <strong>Use 2nd Generation Cloud Functions:</strong></p><p>To effectively work with multiple Firestore databases, you’ll need to use <strong>2nd Generation Cloud Functions</strong>. These functions are designed to support multiple Firestore instances, providing greater flexibility and scalability for your applications.</p><p><strong>Writing Code for Your Cloud Function with Multiple Firestore Databases</strong></p><p>After creating your Cloud Function and connecting it to multiple Firestore instances, the next step is to implement the function logic. In this section, we’ll look at how to write a function that listens for Firestore events, handles multiple databases, and utilizes <strong>Protocol Buffers (protobuf)</strong> for efficient data handling.</p><p><strong>Sample Cloud Function Code</strong></p><p>Here’s an example of how you can structure your index.js to listen for Firestore events and work with multiple Firestore databases:</p><pre>const functions = require(&#39;@google-cloud/functions-framework&#39;);<br>const admin = require(&quot;firebase-admin&quot;);<br>const { getFirestore } = require(&#39;firebase-admin/firestore&#39;);<br>const protobuf = require(&#39;protobufjs&#39;);<br><br>// Initialize Firebase Admin SDK<br>const app = admin.initializeApp();<br><br>// Connect to multiple Firestore shards<br>const firebaseShard1 = getFirestore(app);  // Default Firestore instance<br>const firebaseDb2 = getFirestore(app, &quot;firestore-db-2&quot;);  // Second Firestore instance<br><br>// Define Cloud Function triggered by a Firestore event<br>functions.cloudEvent(&#39;onDemoFunction&#39;, async (cloudEvent) =&gt; {<br>  console.log(`Function triggered by event on: ${cloudEvent.source}`);<br>  console.log(`Event type: ${cloudEvent.type}`);<br><br>  // Load protobuf schema<br>  console.log(&#39;Loading protos...&#39;);<br>  const root = await protobuf.load(&#39;data.proto&#39;);<br>  const DocumentEventData = root.lookupType(<br>    &#39;google.events.cloud.firestore.v1.DocumentEventData&#39;<br>  );<br><br>  // Decode Firestore event data using protobuf<br>  console.log(&#39;Decoding data...&#39;);<br>  const firestoreReceived = DocumentEventData.decode(cloudEvent.data);<br>   <br>  console.log(JSON.stringify(firestoreReceived.value, null, 2));<br>  const documentData = firestoreReceived.value.fields;<br>  console.log(&#39;Document data received:&#39;, documentData);<br><br>  // Use parsed document data for business logic<br>  const parsedDocumentData = parseFirestoreDocument(documentData);<br>  console.log(&#39;Parsed document data:&#39;, parsedDocumentData);<br><br>  // Example: Perform operations on a specific Firestore db<br>  const docRef = firebaseDb2.collection(&#39;firestoredb2Collection&#39;).doc(&#39;demoDoc&#39;);<br>  await docRef.set({ ...parsedDocumentData });<br><br>  console.log(&#39;Document successfully written to firestoreDb2&#39;);<br>});<br><br>// Helper function to parse Firestore document fields<br>function parseFirestoreDocument(data) {<br>  const parsedData = {};<br>  for (const key in data) {<br>    parsedData[key] = data[key].stringValue || data[key].integerValue || null;<br>  }<br>  return parsedData;<br>}</pre><p>Google has provided comprehensive data.proto file along with other helper functions for decoding Firestore document events in protobuf format. These files define the structure and fields necessary for handling Firestore events such as document snapshots, update masks, and changes. You can find this specific proto file, which includes the structure of Firestore event data, in the official Google repository: <a href="https://github.com/googleapis/google-cloudevents/blob/main/proto/google/events/cloud/firestore/v1/data.proto">Firestore Event Data Protobuf</a>.</p><p>In your Cloud Function, you can import this proto file, as demonstrated in the screenshot, where the file imports essential components like struct.proto, timestamp.proto, and latlng.proto for handling complex data types such as timestamped fields and geographical locations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m6292d3BrgCeysWSvHAKUg.png" /></figure><p>Now, after writing your logic and connecting to the required Firestore database, all that’s left is to save and deploy your Cloud Function. With a single click on <strong>“Save and Redeploy”</strong>, your function is ready to serve! Anytime an event — like a new document creation or an update — happens in your Firestore database, your Cloud Function will trigger, perform the necessary actions, and log the details.</p><blockquote><strong>Note:</strong> If you create a Firestore database through the Firebase Console, you may run into issues accessing that instance from Cloud Functions, especially with HTTP request triggers. To avoid these hiccups, it’s best to create your Firestore database directly through the Google Cloud Console or use the command line with the following command:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*swWgvsUd_Fv3igI0McmTkA.png" /></figure><pre>gcloud alpha firestore databases create --database=NAME --location=LOCATION --type=firestore-native --delete-protection    </pre><p>I want to extend my heartfelt thanks to Dinesh for his invaluable assistance in exploring Cloud Functions with Firestore. His insights and support have made a significant difference in my understanding and implementation of this powerful toolset.</p><p>That’s it for now! I hope you find this guide helpful. If you have any questions or if something isn’t clear, feel free to leave a comment. Thanks for reading! 🙌🙏</p><p>References:</p><ul><li><a href="https://firebase.google.com/docs/firestore/extend-with-functions-2nd-gen">https://firebase.google.com/docs/firestore/extend-with-functions-2nd-gen</a></li><li><a href="https://stackoverflow.com/questions/77061688/how-can-i-connect-to-a-non-default-firestore-database-using-node-using-multiple">https://stackoverflow.com/questions/77061688/how-can-i-connect-to-a-non-default-firestore-database-using-node-using-multiple</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aa38a234e20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rapido Navigation: Getting You There, Wherever You’re Going]]></title>
            <link>https://medium.com/rapido-labs/rapido-navigation-getting-you-there-wherever-youre-going-867e1993c80f?source=rss-cf0c40c14ca4------2</link>
            <guid isPermaLink="false">https://medium.com/p/867e1993c80f</guid>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[safety]]></category>
            <category><![CDATA[ride-hailing]]></category>
            <category><![CDATA[ridesharing]]></category>
            <category><![CDATA[maps]]></category>
            <dc:creator><![CDATA[Inder singh]]></dc:creator>
            <pubDate>Wed, 13 Mar 2024 06:36:32 GMT</pubDate>
            <atom:updated>2024-03-13T06:36:32.331Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/u/1f7d6a714f03">Rapido</a> is one of the largest ride-hailing service providers in India, facilitating millions of rides daily.</p><ul><li>Do you know how the Captain (the driver) reaches your location when you book a ride?</li><li>Do you know how it takes you to your destination without asking for directions?</li><li>Do you know how you receive <strong>safety alerts</strong> in case of route deviations or when the vehicle is not moving?</li></ul><p>The secret sauce behind all of this and the smooth navigation experience is a custom navigation solution called the <strong>Rapido Navigation SDK</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u-aqLAAy78PlWRSkWCC_Ug.png" /><figcaption><a href="https://www.freepik.com/premium-photo/medium-shot-woman-holding-smartphone_14960777.htm#fromView=search&amp;page=1&amp;posit[%E2%80%A6]451-652c980656a3?log-in=email">Image Src</a></figcaption></figure><p><strong>Rapido Navigation SDK </strong>is the backbone of navigation functionality within the captain app, enabling real-time route optimization, turn-by-turn directions, and traffic-aware routing. Earlier we partnered with a single navigation service provider to power our app’s navigation features. However, with the evolution of technology and increasing demand for customization, flexibility, and reliability, we are now leveraging Navigation capabilities from multiple providers.</p><p>Integrating Navigation SDKs from multiple providers offers several advantages. Firstly, it reduces dependency on a single provider, mitigating the risk of service disruptions or performance issues. Secondly, we can tailor their navigation experience based on specific user preferences, geographical regions, or pricing considerations. Thirdly, it fosters healthy competition among navigation service providers, leading to continuous innovation and improvement in navigation services.</p><p><strong>Key Features of Rapido Navigation SDK are:</strong></p><ul><li><strong>Run Navigation in the background:</strong> As soon as the customer starts the booking journey, we track the user’s movement, even if the captain is not actively using the navigation screen.</li><li><strong>Send Safety Alerts:</strong> If a route deviation occurs during the ride or the vehicle remains stationary for a specific time interval, we notify the customer to ensure their safety.</li><li><strong>Navigation foreground:</strong> Start the navigation screen, which will provide turn-by-turn directions to the user. It also displays ETA(Estimated Time of Arrival), remaining distance, time, and traffic information.</li><li><strong>Capability to navigate via Start and End location:</strong> The navigation should begin by entering the start and end locations.</li><li><strong>Capability to navigate via polyline imposition:</strong> The navigation should adhere strictly to the route specified by the provided polyline geometry.</li><li><strong>Capability to navigate via waypoints imposition:</strong> The navigation should strictly follow the route specified by the provided waypoints.</li><li><strong>Location Updates:</strong> We have a feature for editing the pick-up and drop-off points during navigation. To handle this, it has the capability of updating locations during the navigation.</li><li><strong>Capability of Switching Providers:</strong> We can switch providers based on business needs, as some providers provide specific features critical for a business at particular locations or times, with just a toggle.</li></ul><h3><strong>Challenges</strong></h3><p>While building this SDK, we encountered several challenges:</p><ul><li>Selecting and evaluating a provider with the capabilities required for our business use cases, such as imposing a route to navigate and providing alerts for route deviations.</li><li>Customizing the UI/UX to ensure a seamless experience for captains, even if there is a switch in the mapping provider so that it does not feel like using different maps.</li></ul><h3><strong>Customer Safety Alerts</strong></h3><p>At <a href="https://medium.com/u/1f7d6a714f03">Rapido</a>, we prioritize the safety and security of our valued customers. We understand the importance of providing a secure and reliable travel experience, which is why we have implemented a comprehensive range of safety measures and protocols.</p><ul><li><strong>Route Deviation Alert:</strong> If the captain chooses a different route from the predetermined one, the navigation SDK will automatically generate an alert for the customer to verify its safety and will also notify the captain to adhere to the recommended route.</li></ul><blockquote>How does the SDK generate a route deviation alert?</blockquote><blockquote>Upon any route changes initiated by the captain from the predetermined path, our system receives callbacks such as <strong>onReRoutingRequested</strong> and <strong>onNewRoute</strong> from the providers. These callbacks provide us with updated route information. We then analyze the alterations in distance and time against specific thresholds. If these changes surpass the designated thresholds, alert data is promptly sent to our backend. Following a thorough verification process, the relevant information is forwarded to the customer for their awareness.</blockquote><pre>override fun onReRoutingRequested() {<br>    navigationUpdatesSharedFlow.tryEmit(Navigation.OnRerouting)<br>}<br><br>override fun onNewRoute(polyline: String?) {<br>    navigationUpdatesSharedFlow.tryEmit(Navigation.OnNewRoute(polyline))<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pQC_3QrBOa3XlKmgRHOvrg.png" /></figure><ul><li><strong>Vehicle Stationary Alert:</strong> When the vehicle remains inactive or stationary for a specified duration, the SDK initiates an alert mechanism. This alert serves to notify the customer about the prolonged inactivity of the vehicle, prompting them to take necessary action to verify its safety or address any potential issues.</li></ul><blockquote>The vehicle stationary alert is generated as follows:</blockquote><blockquote>We receive periodic updates on the route progress from the provider through the <strong>onRouteProgress</strong> callback, which includes the remaining time and distance to the destination. If the remaining time and distance do not change for a specific threshold duration, we start a timer to monitor the duration of vehicle inactivity. Additionally, based on location criteria, if there is no change in the remaining time and distance after a certain duration, we trigger a vehicle stationary alert. This alert is sent to the backend for verification, and upon confirmation, it is relayed to the customer. Any change in distance and time resets the timer for monitoring vehicle activity.</blockquote><pre>override fun onRouteProgress(routeProgress: RouteProgress) {<br>        navigationUpdatesSharedFlow.tryEmit(Navigation.OnRouteProgress(routeProgress)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eNDD1eS-Wp-hIJX5Wlj-7w.png" /></figure><p>All these alert mechanisms operate through the <strong>Background Navigation feature</strong>, ensuring safety checks are conducted even when the captain is not actively using the navigation system. This means that safety protocols continue to function behind the scenes, monitoring the situation, and triggering alerts to the customer as needed, regardless of the captain’s navigation activity.</p><h3><strong>UI Customization</strong></h3><p>One of our primary objectives is to maintain a consistent user interface (UI) and user experience (UX) for our maps across various providers. This consistency is crucial to prevent captains from encountering navigation difficulties when providers change. Achieving this consistency involves a significant learning curve regarding how different mapping systems operate.</p><p>Here are some key aspects and challenges we’ve encountered in implementing consistent maps UI/UX:</p><p><strong>Provider Integration:</strong></p><p>Integrating maps from different providers requires understanding the unique features, APIs, and data formats of each provider’s mapping system.</p><p><strong>UI Design Guidelines:</strong></p><p>We establish UI design guidelines to ensure a consistent look and feel across different mapping platforms. This involves harmonizing visual elements, such as map controls, icons, and colour schemes, to create a seamless user experience regardless of the underlying mapping technology.</p><p><strong>Zoom Level Optimization</strong>:</p><p>Determining the appropriate zoom level in maps is a crucial aspect of our navigation system. Setting the correct zoom level is essential to ensure optimal visibility of the route ahead for captains. If the zoom level is too high (zoomed in), it can make it challenging for captains to see the route properly. Conversely, if the zoom level is too low (zoomed out), essential information such as landmarks, building details, or lane information may not be visible.</p><p>After numerous iterations and testing, we have identified specific zoom-level settings that best suit our use cases. These settings strike a balance between providing captains with a clear view of the route ahead while also displaying necessary contextual information such as landmarks and building details. By optimizing the zoom level, we aim to enhance the navigational experience and improve overall usability for captains navigating through various environments.</p><p><strong>Polyline Thickness Optimization:</strong></p><p>To ensure that the route polyline is clearly visible to the captain, we’ve implemented a dynamic polyline thickness adjustment based on the zoom level, road width, and area characteristics. This optimization process involves iterating through various combinations to determine specific values that provide optimal visibility at each zoom level. By considering factors such as the zoom level, road width, and area characteristics, we can dynamically adjust the thickness of the polyline to ensure it remains clear and easily visible to the captain. Through rigorous testing and iteration, we’ve identified specific values that are fixed at each zoom level to provide the best possible visibility without overwhelming the map display.</p><p><strong>Camera Tracking:</strong></p><p>Zooming in during turns and zooming out afterwards. This feature allows the camera to automatically zoom in when the vehicle approaches a turn, providing enhanced visibility and detail for the captain during critical manoeuvres. After completing the turn, the camera zooms out to provide a broader view of the surroundings, optimizing the navigational experience for smoother and safer navigation.</p><p><strong>Ahead Location Tracking:</strong></p><p>This feature tracks the user’s position ahead along the intended route rather than focusing solely on the current location. By anticipating the user’s movements and trajectory, it provides a proactive navigation experience, ensuring timely guidance and assistance for upcoming turns and manoeuvres.</p><p><strong>Map Tilt Optimization:</strong></p><p>After several iterations, we’ve addressed the issue of high memory consumption associated with map tilt by optimizing the rendering process. By carefully balancing the amount of information displayed with resource consumption, we’ve arrived at a value that ensures an optimal user experience.</p><p>Overall, by investing in understanding the nuances of different mapping technologies and implementing robust UI/UX design principles, we strive to deliver a consistent and intuitive navigation experience for captains, irrespective of the provider used.</p><p><strong>High-Level Design of the SDK</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IzxYpAY_PlBXjn2ujAOsdg.jpeg" /><figcaption>rapido-navigation-sdk</figcaption></figure><ul><li><strong>Navigation Controller:</strong> This is the entry point into the SDK, which exposes functions such as startBackgroundNavigation, startForegroundNavigation, stopNavigation, and initNavigation to the client apps.</li><li><strong>Init SDK:</strong> Initialize the SDK, retrieve the configuration from the backend, cache it, and initialize the provider based on the set configuration.</li><li><strong>NavigationHelper:</strong> This is an internal functionality within the SDK that facilitates routing requests to the appropriate use cases.</li><li><strong>Foreground Navigation Launcher:</strong> It initiates foreground navigation and manages all foreground navigation scenarios. If not already running, it also starts background navigation for non-order-related use cases, such as navigating to nearby petrol stations or ATMs.</li><li><strong>BackgroundNavigation Launcher:</strong> It launches background navigation as soon as the order is mapped.</li><li><strong>Location Updates:</strong> While navigating, if there are changes to the pick-up or drop-off locations, it reroutes to the next destination.</li><li><strong>Register Navigation Updates:</strong> It should emit all navigation events and updates, such as new ETA, distance, and time left, based on the configuration.</li><li><strong>StopNavigation:</strong> When stopping the navigation, it should halt the provider and unregister all listeners.</li><li><strong>Fallbacks:</strong> If the configured provider fails to start, it should fallback to the default navigation provider.</li><li><strong>Localization:</strong> All content displayed on the screen should be localized according to the user’s preferred locale.</li><li><strong>Send Safety Alerts: </strong>If there is any unnecessary route deviation or if a vehicle remains stationary for a specific duration, based on location and other business logic, send safety alerts to our backend, which will then forward them to our customer.</li></ul><blockquote>In part 2 of this article, our focus will be primarily on delving into the technical aspects of the Navigation SDK.</blockquote><p>I want to express gratitude to <a href="https://medium.com/u/37cdb3038123">Satyaraj Moily</a>, <a href="https://medium.com/u/8916dd03077a">Nagavishnu</a>, <a href="https://medium.com/u/6a2c2b1b5275">Ezhil Warner</a>, <a href="https://medium.com/u/425e9c2a49e0">Akhilnallapaneni</a>, and the entire application platform team at Rapido for their assistance and support throughout the development and implementation of this SDK into production.</p><p>I want to extend a sincere thank you to <a href="https://medium.com/u/48b23feedae5">Shrutiunnikrishnan</a> and <a href="https://medium.com/u/b2a7c3d619ea">Ujwal Bagrodia</a> for providing images for this blog.</p><p>That’s it for now, hope it helps! Enjoy, and feel free to leave a comment if something is not clear or if you have questions. Thank you for reading! 🙌🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=867e1993c80f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rapido-labs/rapido-navigation-getting-you-there-wherever-youre-going-867e1993c80f">Rapido Navigation: Getting You There, Wherever You’re Going</a> was originally published in <a href="https://medium.com/rapido-labs">Rapido Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Kotlin Multiplatform Mobile SDK for Location-Related Services]]></title>
            <link>https://medium.com/rapido-labs/building-a-kotlin-multiplatform-mobile-sdk-for-location-related-services-488a2855ab23?source=rss-cf0c40c14ca4------2</link>
            <guid isPermaLink="false">https://medium.com/p/488a2855ab23</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[location]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Inder singh]]></dc:creator>
            <pubDate>Wed, 01 Mar 2023 07:09:03 GMT</pubDate>
            <atom:updated>2023-03-02T07:11:21.954Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9NLflh-MVaNX558ydxkWw.jpeg" /></figure><p>Kotlin Multiplatform Mobile (KMM) has been gaining popularity among mobile app developers. The KMM SDK allows developers to write business logic and share it between different platforms such as Android, iOS, and the web. In this article, we’ll explore how I developed a Kotlin Multiplatform Mobile SDK for location-related services for <a href="https://medium.com/u/1f7d6a714f03">Rapido</a>.</p><p><strong>Background</strong></p><p><a href="https://medium.com/u/1f7d6a714f03">Rapido</a> has been using native mobile development for several years. We have separate codebases for Android and iOS; maintaining them is quite challenging. We also noticed that the code for location-related services was almost identical for both platforms, with a few differences in implementation. We wanted to find a way to share this code between platforms and minimize the overhead of maintaining two separate codebases.</p><p><strong>Kotlin Multiplatform Mobile</strong></p><p>Kotlin Multiplatform Mobile was a perfect solution to our problem. KMM allows developers to write business logic using Kotlin and share it between different platforms. The code can be compiled into platform-specific code, allowing it to run natively on each platform.</p><p><strong>Architecture:</strong> The SDK is built using Kotlin’s multiplatform capabilities, with shared code for location data retrieval and platform-specific implementations for location data. Our SDK uses a Repository Pattern for data retrieval, with the repository layer handling data retrieval from different sources and abstracting it from the presentation layer. We have also implemented a Network Service Layer that handles network calls to our internal backend service and returns the data to the repository layer.</p><p>The SDK’s architecture can be visualized in the following diagram:</p><figure><img alt="High level flow diagram of the location sdk" src="https://cdn-images-1.medium.com/max/1024/1*a4oXFV9j11yty1fc0l639Q.jpeg" /><figcaption>Location Sdk flow diagram</figcaption></figure><p><strong>The SDK provided the following functionalities:</strong></p><ul><li><em>Get current location</em>: This functionality was used to get the user’s current location.</li><li><em>Get the last known location</em>: This functionality was used to get the user&#39;s last known location.</li><li><em>Get address from location</em>: This functionality was used to get the address from the user’s location(Reverse Geocode).</li><li><em>Get location from the address or place id</em>: This functionality was used to get the location from an address or place id(Geocode).</li><li><em>Places Autocomplete</em>: This functionality was used to get the suggestion of address based on the user search</li><li><em>Location Selection</em>: This functionality was used to provide the list of locations near a provided location in request the returned locations can be used as pickup points and sticky locations depending on various use cases</li><li>Many more features in the pipeline 🏗️</li></ul><p><strong>Implementation</strong></p><p>We implemented the SDK using the following steps:</p><ol><li>Create a new Kotlin Multiplatform module.</li><li>Define an interface for location-related services.</li><li>Implement the interface for each platform separately.</li><li>Use the implementation in the common code.</li></ol><p><a href="https://kotlinlang.org/docs/multiplatform-connect-to-apis.html">From official doc</a></p><blockquote>Application that needs to access platform-specific APIs that implement the required functionality, use the Kotlin mechanism of <em>expected and actual declarations</em>.</blockquote><blockquote>With this mechanism, a common source set defines an <em>expected declaration</em>, and platform source sets must provide the <em>actual declaration</em> that corresponds to the expected declaration.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vsQQ_8rD70z51YRH.png" /></figure><p>Let&#39;s dive into the <strong>sample code</strong> of the user&#39;s current location implementation</p><p>In the common section, we have to define the abstraction</p><pre>// Define a data class to store latitude and longitude coordinates<br>data class Location(val latitude: Double, val longitude: Double)<br><br>// Define a common class for location service<br>expect class LocationService() {<br>   suspend fun getCurrentLocation(): Location<br>}</pre><p>In the Android and iOS sections, we have to provide the implementation like this</p><pre>// Implement the LocationService in Android<br>actual class LocationService  {<br><br>    // Initialize the FusedLocationProviderClient<br>    private val fusedLocationClient by lazy {<br>        LocationServices.getFusedLocationProviderClient(RapidoLocationController.getContext() as Context)<br>    }<br><br>    // Implement the getCurrentLocation() method<br>    @SuppressLint(&quot;MissingPermission&quot;) // Assuming location permission check is already handled<br>    actual suspend fun getCurrentLocation(): Location = suspendCoroutine { continuation -&gt;<br>        fusedLocationClient.lastLocation.addOnSuccessListener { location -&gt;<br>            location?.let {<br>                continuation.resume(Location(it.latitude, it.longitude))<br>            } ?: run {<br>                continuation.resumeWithException(Exception(&quot;Unable to get current location&quot;))<br>            }<br>        }.addOnFailureListener { e -&gt;<br>            continuation.resumeWithException(e)<br>        }<br>    }<br>}</pre><pre>// Implement the LocationService in iOS<br>actual class LocationService  {<br><br>    // Define a native CLLocationManager object<br>    private val locationManager = CLLocationManager()<br><br>    // Define an atomic reference to store the latest location<br>    private val latestLocation = AtomicReference&lt;Location?&gt;(null)<br><br>    // Define a custom delegate that extends NSObject and implements CLLocationManagerDelegateProtocol<br>    private class LocationDelegate : NSObject(), CLLocationManagerDelegateProtocol {<br><br>        // Define a callback to receive location updates<br>        var onLocationUpdate: ((Location?) -&gt; Unit)? = null<br><br>        override fun locationManager(manager: CLLocationManager, didUpdateLocations: List&lt;*&gt;) {<br>            didUpdateLocations.firstOrNull()?.let {<br>                val location = it as CLLocation<br>                location.coordinate.useContents {<br>                    onLocationUpdate?.invoke(Location(latitude, longitude))<br>                }<br><br>            }<br>        }<br><br>        override fun locationManager(manager: CLLocationManager, didFailWithError: NSError) {<br>            onLocationUpdate?.invoke(null)<br>        }<br>    }<br><br><br>    // Implement the getCurrentLocation() method<br>    actual suspend fun getCurrentLocation(): Location = suspendCoroutine { continuation -&gt;<br>        locationManager.requestWhenInUseAuthorization()<br>        locationManager.desiredAccuracy = kCLLocationAccuracyBest<br>        locationManager.distanceFilter = kCLDistanceFilterNone<br>        locationManager.startUpdatingLocation()<br><br>        // Define a callback to receive location updates<br>        val locationDelegate = LocationDelegate()<br>        locationDelegate.onLocationUpdate = { location -&gt;<br>            locationManager.stopUpdatingLocation()<br>            latestLocation.value = location<br>            if (location != null) {<br>                continuation.resume(location)<br>            } else {<br>                continuation.resumeWithException(Exception(&quot;Unable to get current location&quot;))<br>            }<br>        }<br><br>        // Assign the locationDelegate to the CLLocationManager delegate<br>        locationManager.delegate = locationDelegate<br>    }<br>}</pre><p>For Android, we used the Fused Location Provider API provided by Google Play Services to get the user’s location. For iOS, we used the Core Location framework to get the user’s location.</p><p>We used the Geocoder API provided by Google Play Services to get the address from the user’s location for Android. For iOS, we used the CLGeocoder class provided by the Core Location framework to get the address from the user’s location.</p><p><strong>Testing</strong></p><p>We tested the SDK on both Android and iOS platforms. We used JVM-based libraries for testing like <a href="https://mockk.io/">mockk</a> ,kotlin(“test”) , and coroutines-test for the common codeto ensure the functionality worked as expected.</p><p><strong>Exporting</strong></p><p>Exporting a KMM module involves creating a library that can be used in both Android and iOS projects</p><p><strong><em>Exporting a KMM module for Android</em></strong></p><p>Exporting a KMM module for Android requires creating an AAR (Android Archive) library that can be used in Android projects. The following steps outline how to create an AAR library for a KMM module:</p><ul><li>Create a publish.gradle file, add the following code</li></ul><pre>apply plugin: &#39;maven-publish&#39;<br><br>def LIB_GROUP_ID = &#39;com.example.company&#39;<br>def LIB_ARTIFACT_ID = &#39;locationsdk&#39;<br>def LIB_VERSION = &#39;1.0.0&#39;<br>def LIB_VERSION_SNAPSHOT = &#39;1.0.0-SNAPSHOT&#39;<br>def USER_NAME = System.getenv(&quot;USERNAME&quot;)<br>def PASSWORD = System.getenv(&quot;PASSWORD&quot;)<br><br><br>android {<br>    publishing {<br><br>        singleVariant(&quot;debug&quot;) {<br>            withSourcesJar()<br>            withJavadocJar()<br>        }<br>        singleVariant(&quot;release&quot;) {<br><br>        }<br>    }<br>}<br><br><br>afterEvaluate {<br>    publishing {<br>        repositories {<br>            maven {<br>                name = &quot;GitHubPackages&quot;<br>                url = uri(&quot;https://maven.pkg.github.com/repository_path&quot;)<br>                credentials {<br>                    username = USER_NAME<br>                    password = PASSWORD<br>                }<br>            }<br>        }<br><br>        publications {<br>            release(MavenPublication) {<br>                from components.release<br>                groupId LIB_GROUP_ID<br>                artifactId LIB_ARTIFACT_ID<br>                version LIB_VERSION<br>            }<br><br>            debug(MavenPublication) {<br>                from components.debug<br>                groupId LIB_GROUP_ID<br>                artifactId LIB_ARTIFACT_ID<br>                version LIB_VERSION_SNAPSHOT<br>            }<br>        }<br>    }<br>}</pre><ul><li>In the module’s build.gradle.kts file, add the following code to the android section:</li></ul><pre>apply(from = &quot;$rootDir/locationsdk/publish.gradle&quot;)</pre><p>This code adds a Maven publication that can be used to generate an AAR library.</p><ul><li>In the same build.gradle.kts file, add the following code to the repositories section:</li></ul><pre>repositories {<br>    mavenCentral()<br>    mavenLocal()<br>}</pre><p>This code adds the Maven Central and Maven Local repositories, which are required to publish the AAR library.</p><ul><li>Open the Gradle panel in Android Studio and navigate to the KMM module.</li><li>Run the “publishToMavenLocal” task. This will publish the module to the local Maven repository, found in the “build/publications/Release/” folder.</li><li>You can run “publishReleasePublicationToGitHubPackagesRepository” to publish to the GitHub packages. (this can be automated via git-workflows as well)</li><li>Share the AAR file with other developers or add it to your Android project’s dependencies.</li></ul><p><strong><em>Exporting a KMM module for iOS</em></strong></p><p>Exporting a KMM module for iOS requires creating a framework that can be used in Xcode. The following steps outline how to create a framework for a KMM module.</p><ul><li>Add the following code to the kotlin block of the build.gradle.kts file</li></ul><pre> val xcf = XCFramework()<br>    val iosTargets = listOf(iosX64(), iosArm64(), iosSimulatorArm64())<br><br>    iosTargets.forEach {<br>        it.binaries.framework {<br>            baseName = &quot;MyFramework&quot;<br>            xcf.add(this)<br>        }<br>    }</pre><ul><li>Run ./gradlew assembleXCFramework in the terminal, this will generate the xcFramework in the build/XCFrameworks folder of the app which will contain both the release and debug framework</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8qCobygqFfFvdpO3TUX6mQ.png" /></figure><ul><li>XCFramworks can be integrated into the existing iOS project as a frameworks, follow <a href="https://kotlinlang.org/docs/multiplatform-mobile-integrate-in-existing-app.html#connect-the-framework-to-your-ios-project">this</a> for details</li><li>Alternatively, you can use cocoapods or SPM to pull the dependencies in the existing project (we are using this approach)</li><li>For <a href="https://kotlinlang.org/docs/native-cocoapods.html">cocoapods</a> integration add the following code in the build.gradle.kts file of the multiplatform module.</li></ul><pre>plugins {<br>    kotlin(&quot;multiplatform&quot;) <br>    kotlin(&quot;native.cocoapods&quot;)<br>}<br><br>kotlin {<br>    cocoapods {<br>        // Required properties<br>        // Specify the required Pod version here. Otherwise, the Gradle project version is used.<br>        version = &quot;1.0&quot;<br>        summary = &quot;Some description of the module&quot;<br>        homepage = &quot;Link to the repository&quot;<br><br>        // Optional properties<br>        // Configure the Pod name here instead of changing the Gradle project name<br>        name = &quot;LocationSdkKmm&quot;<br><br>        framework {<br>            // Required properties<br>            // Framework name configuration. Use this property instead of deprecated &#39;frameworkName&#39;<br>            baseName = &quot;locationSdk&quot;<br><br>            // Optional properties<br>            // Specify the framework linking type. It&#39;s dynamic by default.<br>            isStatic = false<br>        }<br><br>        // Maps custom Xcode configuration to NativeBuildType<br>        xcodeConfigurationToNativeBuildType[&quot;DEBUG&quot;] = NativeBuildType.DEBUG<br>        xcodeConfigurationToNativeBuildType[&quot;RELEASE&quot;] = NativeBuildType.RELEASE<br>    }<br>}</pre><ul><li>Re-import the project.</li><li>This will generate the podspec file in the project as below.</li></ul><pre>Pod::Spec.new do |spec|<br>    spec.name                     = &#39;LocationSdkKmm&#39;<br>    spec.version                  = &#39;1.0.0&#39;<br>    spec.homepage                 = &#39;Link to the repository&#39;<br>    spec.source                   = { :http=&gt; &#39;&#39;}<br>    spec.authors                  = &#39;&#39;<br>    spec.license                  = &#39;&#39;<br>    spec.summary                  = &#39;Some description of the module&#39;<br>    spec.vendored_frameworks      = &#39;shared/build/XCFrameworks/release/shared.xcframework&#39;<br>    spec.libraries                = &#39;c++&#39;<br>   <br>    spec.pod_target_xcconfig = {<br>        &#39;KOTLIN_PROJECT_PATH&#39; =&gt; &#39;:locationSdk&#39;,<br>        &#39;PRODUCT_MODULE_NAME&#39; =&gt; &#39;:locationSdk&#39;,<br>    }<br>                <br>end</pre><ul><li>Push the code along with the xcframework (it can be automated as well by the podspec script ) to the repository and create a git-tag with release version</li><li>In the existing iOS project pod file add the dependencies like the code below</li></ul><pre>  pod &#39;locationSdk&#39;, :git =&gt; &#39;https://github.com/repo_path&#39;, :branch =&gt; &#39;master&#39;, :tag  =&gt; &#39;1.0.0&#39;</pre><ul><li>Run “pod install” in the terminal, it will pull the framework and add it to the existing project</li></ul><p><strong>Conclusion</strong></p><p>In conclusion, we were able to develop a Kotlin Multiplatform Mobile SDK for location-related services for <a href="https://medium.com/u/1f7d6a714f03">Rapido</a>. The SDK allowed us to share code between platforms, reducing the overhead of maintaining separate codebases for Android and iOS. KMM proved to be an efficient tool for building a cross-platform mobile SDK. We plan to continue exploring KMM and using it in other areas of our application.</p><p>I want to thank <a href="https://medium.com/u/cba8d6782e3b">Suryakant Sharma</a> &amp; <strong>sharanabasappa</strong> from the iOS team, who helped in the integration with the iOS app.</p><p>That’s it for now, hope it helps! Enjoy, and feel free to leave a comment if something is not clear or if you have questions. Thank you for reading! 🙌🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=488a2855ab23" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rapido-labs/building-a-kotlin-multiplatform-mobile-sdk-for-location-related-services-488a2855ab23">Building a Kotlin Multiplatform Mobile SDK for Location-Related Services</a> was originally published in <a href="https://medium.com/rapido-labs">Rapido Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit test — Argument Captor with Mockk]]></title>
            <link>https://proandroiddev.com/unit-test-argument-captor-with-mockk-e7e1309bbf5a?source=rss-cf0c40c14ca4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7e1309bbf5a</guid>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[kotin]]></category>
            <category><![CDATA[mockk]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[argument-captor]]></category>
            <dc:creator><![CDATA[Inder singh]]></dc:creator>
            <pubDate>Mon, 31 Oct 2022 13:58:47 GMT</pubDate>
            <atom:updated>2022-11-04T08:18:50.955Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unit test — Kotlin functions(with listeners, lambda) with Mockk</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDkSIyiIimevgTZXFGNgbg.png" /></figure><p>Testing is an essential part of the software development process. A unit test generally exercises the functionality of the smallest possible unit of code (which could be a method or class) in a repeatable way. You should add unit tests when you need to verify the logic of a specific code in your app.</p><p>The scope of this article is to explain the testing of functions with listeners and functions taking lambda as arguments. If you want to learn the basics of testing, there are some good tutorials available:</p><ul><li><a href="https://www.raywenderlich.com/195-android-unit-testing-with-mockito">https://www.raywenderlich.com/195-android-unit-testing-with-mockito</a></li><li><a href="https://proandroiddev.com/understanding-unit-tests-for-android-in-2021-71984f370240">https://proandroiddev.com/understanding-unit-tests-for-android-in-2021-71984f370240</a></li></ul><p><strong>Note</strong>: In this article, <a href="https://mockk.io/"><strong>mockk</strong></a> is used for mocks; the same concepts will also apply to other mocking tools.</p><p>Consider a function that has a listener like getCurrentLocation in the below gist.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3390473edcc0f9261197e8e83ce7a94/href">https://medium.com/media/f3390473edcc0f9261197e8e83ce7a94/href</a></iframe><p>The unit test for the getCurrentLocation function in which the location returned successfully (i.e. the addOnSuccessListener gets called) is :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e04adc8425469f4129d4df2413d7e79d/href">https://medium.com/media/e04adc8425469f4129d4df2413d7e79d/href</a></iframe><p>Let’s understand the test. whenever getCurrentLocation will be called, addOnSuccessListener should be invoked, to do that we have to use argument captor.</p><blockquote><em>ArgumentCaptor</em> allows us to capture an argument passed to a method to inspect it. This <strong>is especially useful when we can’t access the argument outside of the method we’d like to test.</strong></blockquote><p>There are two ways to capture arguments: using CapturingSlot&lt;TYPE&gt; and using MutableListOf&lt;TYPE&gt;.</p><p>CapturingSlot allows to capture only one value, for our case, this will work if you have multiple values you can use MutableListOf&lt;TYPE&gt;.</p><pre>val slot = slot&lt;OnSuccessListener&lt;Location&gt;&gt;()</pre><pre>every { locationTaskMock.addOnSuccessListener(capture(slot))}</pre><pre>answers { slot.captured.onSuccess(locationTaskMock.result)                       locationTaskMock           <br>}</pre><p>This creates a slot and a mock and set expected behavior following way: in case locationTaskMock.addOnSuccessListener is called, then OnSuccessListener is captured to the slot locationTaskMock.result is answered.</p><pre>val result =                currentLocationCoroutineWrapperImpl.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY)</pre><p>Now, this function can be asserted easily.</p><p>Let&#39;s take another example wherein a function that takes a <strong><em>higher-order function</em></strong> as an argument like connect(connectionListener: (isConnected: Boolean) -&gt; Unit)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af2c59e3356b584a7d419b779173a025/href">https://medium.com/media/af2c59e3356b584a7d419b779173a025/href</a></iframe><p>Unit test for the above function connect is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/160e5232b72358845366625d44265262/href">https://medium.com/media/160e5232b72358845366625d44265262/href</a></iframe><pre>every { <br>connectRemote<br>.connect(captureLambda&lt;(isConnected: Boolean) -&gt; Unit&gt;()) } <br>answers {            <br>lambda&lt;(isConnected: Boolean) -&gt; Unit&gt;().captured.invoke(true)        }</pre><p>Here also, in case connectRemote.connect is called then connectionListener: (isConnected: Boolean) -&gt; Unit lambda is captured and true is returned.</p><p>then highOrderDemo.connect can be asserted via</p><pre>highOrderDemo.connect { assertEquals(it, true) }</pre><p>Update:</p><p>We can write tests for the above two methods without argument captor as well in the following way:</p><ul><li><strong><em>Listener</em></strong></li></ul><pre><em>every </em><strong>{ </strong>locationTaskMock.addOnSuccessListener(any()) <strong>} </strong>answers <strong>{<br>    </strong>firstArg&lt;OnSuccessListener&lt;Location&gt;&gt;().onSuccess(locationTaskMock.<em>result</em>)<br>    locationTaskMock<br><strong>}</strong></pre><ul><li><strong><em>Higher-order function</em></strong></li></ul><pre><em>every </em><strong>{ </strong>connectRemote.connect(any()) <strong>} </strong>answers <strong>{<br>    </strong>firstArg&lt;(isConnected: Boolean) -&gt; Unit&gt;().invoke(true)<br><strong>}</strong></pre><p>That’s it for now, I hope it helps! Enjoy and feel free to leave a comment if something is not clear or if you have questions. Thank you for reading! 🙌🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7e1309bbf5a" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/unit-test-argument-captor-with-mockk-e7e1309bbf5a">Unit test — Argument Captor with Mockk</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WorkManager with Android Libraries]]></title>
            <link>https://medium.com/rapido-labs/workmanager-with-android-libraries-f342f1571805?source=rss-cf0c40c14ca4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f342f1571805</guid>
            <category><![CDATA[android-libraries]]></category>
            <category><![CDATA[android-sdk]]></category>
            <category><![CDATA[workmanager]]></category>
            <category><![CDATA[android-workmanager]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Inder singh]]></dc:creator>
            <pubDate>Tue, 07 Jun 2022 06:53:08 GMT</pubDate>
            <atom:updated>2022-06-09T07:45:30.992Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Android Library with WorkManager" src="https://cdn-images-1.medium.com/max/1024/1*NAn8Ux_gb5HZjPXQRVesZA.png" /></figure><p><a href="https://developer.android.com/reference/androidx/work/WorkManager">WorkManager</a> is a powerful jetpack library for persistent work. Scheduled work is guaranteed to be executed sometime after its <a href="https://developer.android.com/reference/androidx/work/Constraints">constraints</a> (like metered network, the battery charging, etc.) are met. WorkManager allows observation of work status and the ability to create a complex chain of work.</p><p>There are numerous blogs and tutorials available for WorkManager usage in android applications with WorkManagerinitialization at the app startup time or <a href="https://developer.android.com/topic/libraries/architecture/workmanager/advanced/custom-configuration#on-demand">on-demand initialization</a> like the one below</p><p><a href="https://medium.com/androiddevelopers/introducing-workmanager-2083bcfc4712">Introducing WorkManager</a></p><p>But very few are available on how to use WorkManager in the right way within a SDK.</p><p>If workers have custom dependencies, then we have to provide the <a href="https://developer.android.com/reference/androidx/work/WorkerFactory">WorkerFactory</a> to the WorkManager through which it will do the initialization of workers. WorkerFactory we have to provide at the time of initialization of the singleton WorkManager. You can read more about WorkManager custom initialization <a href="https://medium.com/androiddevelopers/customizing-workmanager-fundamentals-fdaa17c46dd2">here</a>.</p><p>The problem comes when we want to use the WorkManager in the android library like-</p><ul><li>WorkManager is a singleton. So it can be initialized only once, either in-app or in the library.</li><li>If you are using workers with custom dependencies, then you have to provide a WorkerFactory to the c<a href="https://developer.android.com/reference/androidx/work/Configuration">onfiguration</a> at the time of custom initialization. This can be a d<a href="https://developer.android.com/reference/androidx/work/DelegatingWorkerFactory">elegatingWorkerFactory</a> which delegates to other factories, but all factories still need to register with the single delegator. We have to expose the WorkerFactory to the app so that it can be used at the time of initialization.</li></ul><p>We had the same set of issues while working in my current organization, <a href="https://medium.com/u/980a74a07803">Rapido</a>.</p><p>We are developing an SDK (comms-SDK) for facilitating communication between the platform and the apps which will be used in the Rider (we call them Captain) app wherein we are periodically syncing data to the server, for that purpose, we used an WorkManager in the library.</p><p>We don&#39;t want to enforce our apps (which use comms-SDK) to use WorkManager, and they should not know the internal implementation of the library (WorkerFactory).While finding the solution to this problem, we landed on the awesome <a href="https://developer.squareup.com/blog/workmanager-for-background-work-in-libraries/">square team blog</a> where they also had a similar issue with their logging SDK.</p><p>Let&#39;s go to the solution now.</p><p><strong>Problem 1:</strong> WorkManager initialization(w.r.to the app using our library)</p><p><strong>Solution:</strong> For this, the solution was simple, we try to get the instance of WorkManager in the library, if we get an exception like</p><pre>Caused by: java.lang.IllegalStateException: WorkManager is not initialized properly.  The most likely cause is that you disabled WorkManagerInitializer in your manifest but forgot to call WorkManager#initialize in your Application#onCreate or a ContentProvider.</pre><p>Then only initialize the WorkManager in the library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3a5315ea2ba96b45b20b2aca0e26120/href">https://medium.com/media/d3a5315ea2ba96b45b20b2aca0e26120/href</a></iframe><p><strong>Problem 2</strong>: Launching Workers with custom dependencies from the library.</p><p><strong>Solution: </strong>If we dig deeper into the WorkManager code, we can see that if WorkerFactory is not provided at the time of initialization of the WorkManager for a particular Worker, then it uses the default WorkerFactory which initializes the Workers via reflection until it has no custom dependencies.</p><pre>if (builder.mWorkerFactory == null) {<br>    mWorkerFactory = WorkerFactory.<em>getDefaultWorkerFactory</em>();<br>} else {<br>    mWorkerFactory = builder.mWorkerFactory;<br>}</pre><p>This means we can create another worker (say, ProxyWorker) with no custom dependency, which will be invoked by WorkManager, and we can use this Worker to invoke other Workers with custom dependency in the library via delegateWorkerFactory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe61ce812c98137312d1120e3538eaa3/href">https://medium.com/media/fe61ce812c98137312d1120e3538eaa3/href</a></iframe><p>ProxyWorker can be configured like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd149f9dcbd9a2ad184798e02053ce53/href">https://medium.com/media/dd149f9dcbd9a2ad184798e02053ce53/href</a></iframe><p>We can schedule and stop the ProxyWorker in this way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4065f07eaef2e523f90f2e00358578a0/href">https://medium.com/media/4065f07eaef2e523f90f2e00358578a0/href</a></iframe><p>And that’s it. Now WorkManager will work independently with the app using your library.</p><p>I would like to thank <a href="https://www.linkedin.com/in/puneet-setia-7035b189/">Puneet</a>, for the guidance and feedback.</p><p>That’s it for now, hope it helps! Enjoy and feel free to leave a comment if something is not clear or if you have questions. Thank you for reading! 🙌🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f342f1571805" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rapido-labs/workmanager-with-android-libraries-f342f1571805">WorkManager with Android Libraries</a> was originally published in <a href="https://medium.com/rapido-labs">Rapido Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android App Startup Profiling with Macrobenchmark Library]]></title>
            <link>https://medium.com/@singhinder640/android-app-startup-profiling-with-macrobenchmar-library-55188f41fc06?source=rss-cf0c40c14ca4------2</link>
            <guid isPermaLink="false">https://medium.com/p/55188f41fc06</guid>
            <category><![CDATA[app-startup]]></category>
            <category><![CDATA[android-performace]]></category>
            <category><![CDATA[cold-start]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Inder singh]]></dc:creator>
            <pubDate>Wed, 03 Nov 2021 08:55:37 GMT</pubDate>
            <atom:updated>2021-11-03T09:06:57.519Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2wEvmk4EHMhkv0lu" /><figcaption>Photo by <a href="https://unsplash.com/@aronvisuals?utm_source=medium&amp;utm_medium=referral">Aron Visuals</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For a mobile developer, it is very important to keep an eye on app performance because we have very limited resources in the device, any inefficient solution can lead us to poor user experience whether it is a Non-responsive UI or battery consumption. This article will see how we can measure app startup time using the <a href="https://developer.android.com/studio/profile/macrobenchmark-intro">macro benchmark jetpack library.</a></p><p>App startup time we can get from various analytical sources like <a href="https://developer.android.com/topic/performance/vitals">Android vitals</a>, <a href="https://firebase.google.com/docs/perf-mon">Firebase performance</a>, or Android Debug Bridge (<a href="https://medium.com/androiddevelopers/testing-app-startup-performance-36169c27ee55">there is a great article by Chet Hasse</a>)</p><p>These approaches are simple but have serval drawbacks:</p><ul><li>If we want to make and measure improvement locally while experimenting, we cannot rely on the analytics because here we have to wait for the app to hit users and aggregate the result.</li><li>It will give only one result no idea of runtime variance.</li><li>It will not take into account the state of the device like thermal throttling.</li></ul><p>To address these issues <a href="https://developer.android.com/jetpack">Jetpack</a> team has developed a new tool called <a href="https://developer.android.com/studio/profile/macrobenchmark-intro">Macrobenchmark</a>.</p><p>Steps to integrate microbenchmark in your codebase</p><h4>Add a new module</h4><p>Add a new module to your project. This module holds your Macrobenchmark tests.</p><ol><li>Right-click your project or module in the <strong>Project</strong> panel in Android Studio and click <strong>New &gt; Module</strong>.</li><li>Select <strong>Android Library</strong> in the <strong>Templates</strong> pane.</li><li>Type macrobenchmark for the module name.</li><li>Set <strong>Minimum SDK</strong> to <strong>API 29: Android 10.0 (Q)</strong></li><li>Click <strong>Finish</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rLgtXwq47fI5BiJWmXzYzQ.png" /></figure><h4>Modify the Gradle file</h4><p>Customize the Macrobenchmark module’s build.gradle as follows:</p><ol><li>Change plugin from com.android.library to com.android.test.</li><li>Add additional required test module properties in the android {} block:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5dABl4m_7fLJ5vedMv_baQ.png" /></figure><ol><li>Change all dependencies named testImplementation or androidTestImplementation to implementation.</li><li>Add a dependency on the Macrobenchmark library:</li></ol><ul><li>implementation &#39;androidx.benchmark:benchmark-macro-junit4:1.1.0-alpha03&#39; (please check for the latest version)</li></ul><p>After the android {} block, but before the dependencies {} block, add:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CoOGpA7Kx6aIwfbSTgoxmA.png" /></figure><h4>Simplify directory structure</h4><p>In a com.android.test module, there is only one source directory, for all tests. Delete other source directories, including src/test and src/androidTest, because they aren&#39;t used.</p><p><strong>Create a test class in your module</strong></p><pre>@RunWith(AndroidJUnit4::class)<br>class LaunchTimeBenchmark {<br>   <br>    @get:Rule<br>    val benchmarkRule = MacrobenchmarkRule()<br><br>    @Test<br>    fun startup() = benchmarkRule.measureRepeated(<br>        packageName = &quot;com.example.testapp&quot;,<br>        metrics = <em>listOf</em>(StartupTimingMetric()),<br>        iterations = 5,<br>        startupMode = StartupMode.<em>COLD<br>    </em>) <strong>{<br>        </strong>pressHome()<br>        val intent = Intent()<br>        intent.<em>action </em>= &quot;com.example.testapp.MAIN_SCREEN&quot;<br>        startActivityAndWait(intent)<br>    <strong>}<br></strong>}</pre><p><strong>Add Intent filter in your Activity</strong></p><pre>&lt;intent-filter&gt;<br>    &lt;action android:name=&quot;&quot;com.example.testapp.MAIN_SCREEN&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;<br>&lt;/intent-filter&gt;</pre><p>To benchmark an app (called the <em>target</em> of the macro benchmark), that app must be profileable, which enables reading detailed trace information. You enable this in the &lt;application&gt; tag of the app&#39;s AndroidManifest.xml:</p><pre>&lt;application ... &gt;<br>    &lt;!-- Profileable to enable Macrobenchmark profiling --&gt;<br>    &lt;!-- Suppress AndroidElementNotAllowed --&gt;<br>    &lt;profileable android:shell=&quot;true&quot;/&gt;<br>    ...<br>&lt;/application&gt;</pre><h3>Run the macro benchmark</h3><p>Run the test from within Android Studio to measure the performance of your app on your device. Note that you <strong>must run the test on a physical device</strong>, and not an emulator, as emulators do not produce performance numbers representative of the end-user experience.</p><p>You can also run all benchmarks from the command line by executing the connectedCheck command:</p><pre>$ ./gradlew :macrobenchmark:connectedCheck</pre><p>The result will be shown in the android studio console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uTTvw_e2GBaW0w1FOkV2sA.png" /></figure><p>Click on the hyperlink it will take you to the android profiler</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mnfyDEhn1bpcetoxVpcitA.png" /></figure><p>Yeah, that is done now you can inspect any bottleneck in the code if it’s there and re-run your tests to check the improvements.</p><p>Note:</p><ul><li>It is recommended that you use Macrobenchmark with the latest version of Android Studio (2020.3.1 Beta 4 or higher)</li><li>Add the latest version of the Gradle plugin (7 or higher)</li></ul><p>References :</p><ol><li><a href="https://developer.android.com/studio/profile/macrobenchmark">Android Developers documentation: Macrobenchmark</a></li><li><a href="https://habr.com/ru/company/funcorp/blog/578640/">Jetpack Microbenchmark — Testing Code Performance</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55188f41fc06" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>