<?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 Kevin Alexander Soto on Medium]]></title>
        <description><![CDATA[Stories by Kevin Alexander Soto on Medium]]></description>
        <link>https://medium.com/@kevinalexandersoto?source=rss-141c0eed32c6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*R8REFATW8E4HEElXxSz7Bg.jpeg</url>
            <title>Stories by Kevin Alexander Soto on Medium</title>
            <link>https://medium.com/@kevinalexandersoto?source=rss-141c0eed32c6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 18:58:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kevinalexandersoto/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[How to create a custom Cordova plugin in 2024]]></title>
            <link>https://kevinalexandersoto.medium.com/create-a-custom-cordova-plugin-in-2024-d4fdbedc5291?source=rss-141c0eed32c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4fdbedc5291</guid>
            <category><![CDATA[cordova]]></category>
            <category><![CDATA[ionic]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ionic-framework]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Kevin Alexander Soto]]></dc:creator>
            <pubDate>Sat, 27 Jan 2024 00:22:46 GMT</pubDate>
            <atom:updated>2024-02-06T14:41:29.119Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*38EQhD1N6sPGhpli48zY9A.png" /></figure><p>Developing for IONIC with Cordova or directly in Cordova is a fast way to get a mobile application, the time to develop and the time to market is faster than developing a native App for <strong>Android</strong> and <strong>IOS</strong>. But when you need a native feature and you do not find a plugin made by the community that fits into your needs is a headache.</p><p>The first thing you could do is check the Cordova documentation, which is not clear at all. In this blog, I will explain step by step how I created a <strong>custom Cordova plugin in 2024</strong>. For this blog, I suppose that you already know about native development, it is important, because, you will have to write Android native code(<strong>Java</strong>) and IOS native code (<strong>Swift</strong>).</p><h3><strong>Use PlugMan to create the base</strong></h3><p>1. Install Plugman Globally:</p><ul><li>Command: npm install -g plugman</li></ul><p>This installs the Plugman utility globally on your system, enabling you to manage Cordova plugins from the command line.</p><p>2. Create the Plugin Structure:</p><ul><li>Command: plugman create --name CordovaHelloWorld --plugin_id com-kalex-plugings-helloWorld --plugin_version 1.0.0 --path ./cordovaPlugin</li><li>plugman create: Initiates plugin creation.</li><li>--name CordovaHelloWorld: Assigns the plugin a friendly name.</li><li>--plugin_id com-kalex-plugings-helloWorld: Sets a unique identifier for the plugin.</li><li>--plugin_version 1.0.0: Specifies the initial version number.</li><li>--path ./cordovaPlugin: Designates the directory where the plugin structure will be generated.</li></ul><p>This command constructs the basic plugin structure with essential files and folders within the specified path.</p><p>3. Add Platform Support:</p><ul><li>Command (Android): plugman platform add --platform_name android</li><li>Command (iOS): plugman platform add --platform_name iOS</li></ul><p>These commands enable the plugin to function on the specified platforms (Android and iOS in this case). They generate platform-specific code and configuration within the plugin’s structure.</p><h3>Understand the base of Cordova plugin development</h3><p>Key Components: A Cordova plugin typically consists of:</p><ul><li>JavaScript Interface: A JavaScript file (or files) that provides a JavaScript API for developers to interact with the plugin’s functionality from within their Cordova app.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*wahsn37Uvb7DGZJGzk0zmg.png" /></figure><ul><li>Platform-Specific Code: Native code (e.g., Java for Android, Objective-C for iOS) that implements the actual device interactions for each supported platform. This code resides in platform-specific subdirectories within the plugin structure.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*fApoV3TEAkUoPrw12ZnnhQ.png" /></figure><ul><li>Plugin.xml Metadata: A file containing essential information about the plugin, such as its name, ID, version, supported platforms, JavaScript files, and native code files.</li></ul><h3>Going deep into the native Cordova classes</h3><p>As you can see in the native part, we have the inheritance of specific classes from the Cordova project, in Android we extends from CordovaPlugin, and in IOS we extends from CDVPlugin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*BVCV6VrZTVR-_js1k5UiOQ.png" /><figcaption>Android code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*H8ZpuZBV3cVTQLNoIVkUeg.png" /><figcaption>IOS code</figcaption></figure><p><strong>But, what do these classes bring to the table?</strong></p><p>The <strong>Android side</strong>, gives us access to the webView ,<br>Cordova and preferences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*pP6LEoL0tjNIjDtZEJZPyw.png" /></figure><p>As well, we have access to control the lifecycle methods of the activity</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*Q3dLfD1HZHqGSbqpXXJxYg.png" /></figure><p>We can override these methods in our plugin class to control events of the life cycle in Android.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*gYZh_7S4N466KDknoTdZkg.png" /></figure><p>On the other hand, the <strong>IOS side</strong> gives us access to a webView, webViewEngine, and viewController. We also have access to some lifecycle methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*xoq8JbCwiUq6YTNzYiNnag.png" /></figure><p><em>- (</em><strong><em>void</em></strong><em>)onAppTerminate;</em></p><p><em>- (</em><strong><em>void</em></strong><em>)onMemoryWarning;</em></p><p><em>- (</em><strong><em>void</em></strong><em>)onReset;</em></p><p><em>-(</em><strong><em>void</em></strong><em>)dispose;</em></p><p>but the good ones come when using the Notification Center</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*p8IuvBaAwPcj_b6o83joCA.png" /></figure><p>So, with these methods we have access to the Activity and ViewController on each side, as well as access to the most common and important lifecycle methods in native development.</p><h3>Write the JS bride to communicate with IONIC</h3><p>In resume, this is the code for our JS bride</p><pre>var exec = require(&quot;cordova/exec&quot;);<br><br>exports.sayHello = function (arg0, success, error) {<br>  exec(success, error, &quot;CordovaHelloWorld&quot;, &quot;sayHello&quot;, [arg0]);<br>};<br><br>exports.enable = function (success, error) {<br>  exec(success, error, &quot;CordovaHelloWorld&quot;, &quot;enable&quot;);<br>};<br><br>exports.disable = function (success, error) {<br>  exec(success, error, &quot;CordovaHelloWorld&quot;, &quot;disable&quot;);<br>};</pre><p>lest <strong>break down</strong> this one to understand what is happening.</p><p><strong>1. Importing the </strong><strong>exec Function:</strong></p><ul><li>var exec = require(&quot;cordova/exec&quot;);</li><li>The exec function is the primary way for JavaScript code in a Cordova app to communicate with native platform code (e.g., Java on Android or Objective-C on iOS).</li></ul><p><strong>2. Exporting Plugin Functions:</strong></p><ul><li>exports.sayHello = function (arg0, success, error) { ... }</li><li>This line defines a function named sayHello, exports it, and makes it accessible to other parts of your Cordova app.</li><li>The function takes three arguments:</li><li>arg0: An argument that will be passed to the native code.</li><li>success: A callback function that will be invoked if the native code execution is successful.</li><li>error: A callback function that will be invoked if there&#39;s an error during the native code execution.</li></ul><p><strong>3. Executing Native Code:</strong></p><ul><li>exec(success, error, &quot;CordovaHelloWorld&quot;, &quot;sayHello&quot;, [arg0]);</li><li>This line calls the exec function to execute native code.</li><li>The arguments passed to exec are:</li><li>success: The callback function to be invoked if the native code execution is successful.</li><li>error: The callback function to be invoked if there&#39;s an error.</li><li>“CordovaHelloWorld”: The name of the class that inheritance from Cordova (The classes we talk in the previous part ).</li><li>“sayHello”: The specific method within the native plugin that you want to call.</li><li>[arg0]: An array containing any arguments that need to be passed to the native method (in this case, the arg0 argument from the JavaScript function).</li></ul><h3>Write the Native code</h3><p>Before starting with the code, <strong>my advice</strong> to create the native part is first to create the feature in a native project, test the native feature, and then paste the code to the plugin, <strong>including the imports</strong>.</p><h3><strong>Android code</strong> 🤖</h3><p>Again and to resume the post :) , this is the code in the Android side.</p><pre>public class CordovaHelloWorld extends CordovaPlugin {<br><br>  @Override<br>    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {<br>        if (action.equals(&quot;sayHello&quot;)) {<br>            String message = args.getString(0);<br>            this.sayHello(message, callbackContext);<br><br>            return true;<br>        }<br>        return false;<br>    }<br><br><br>  private void sayHello(String message, CallbackContext callbackContext) {<br>        if (message != null &amp;&amp; message.length() &gt; 0) {<br>            Toast.makeText(webView.getContext(), message, Toast.LENGTH_LONG).show();<br>            callbackContext.success(message);<br>        } else {<br>            callbackContext.error(&quot;Expected one non-empty string argument.&quot;);<br>        }<br>    }<br>}</pre><p>Now, lest break down the code.</p><p><strong>1. Class Definition:</strong></p><ul><li>public class CordovaHelloWorld extends CordovaPlugin { ... }</li><li>The CordovaPlugin class is the base class for custom Cordova plugins on Android, providing the structure for interacting with JavaScript code.</li></ul><p><strong>2. </strong><strong>execute Method:</strong></p><ul><li>@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { ... }</li><li>This method is called when JavaScript code invokes a method from the plugin.</li><li>It receives:</li><li>action: The name of the method being called.</li><li>args: JSONArray of arguments passed from JavaScript.</li><li>callbackContext: A context object used to send results or errors back to JavaScript.</li><li>It checks the action and, if it&#39;s &quot;sayHello&quot;, it calls the sayHello method.</li></ul><p><strong>3. </strong><strong>sayHello Method:</strong></p><ul><li>private void sayHello(String message, CallbackContext callbackContext) { ... }</li><li>This method displays a Toast message with the provided message.</li><li>It checks if the message is valid and either:</li><li>Calls callbackContext.success(message) to send a success response back to JavaScript.</li><li>Calls callbackContext.error(...) to send an error response.</li></ul><h3><strong>IOS code </strong>🍏</h3><p>By default the Cordova plugin is in Objective-c, but we can use Swift in our custom plugin, we need to add the famous notation <em>@objc()</em> and we need a kind of “bride”, called <strong><em>Bridging-Header.h</em></strong><em> F</em>ortunately now day in Cordova 11 this file is generated automatically :) , lest go with the native code.</p><pre>/********* CordovaHelloWorld.m Cordova Plugin Implementation *******/<br><br>import Foundation<br>import Cordova<br>import UIKit<br><br>@objc(CordovaHelloWorld)<br>class CordovaHelloWorld: CDVPlugin {<br><br>    @objc func sayHello(_ command: CDVInvokedUrlCommand) {<br>         var pluginResult = CDVPluginResult(<br>      status: CDVCommandStatus_ERROR<br>    )<br><br>    let msg = command.arguments[0] as? String ?? &quot;&quot;<br><br>    if msg.characters.count &gt; 0 {<br>      let toastController: UIAlertController =<br>        UIAlertController(<br>          title: &quot;&quot;,<br>          message: msg,<br>          preferredStyle: .alert<br>        )<br>      <br>      self.viewController?.present(<br>        toastController,<br>        animated: true,<br>        completion: nil<br>      )<br><br>      DispatchQueue.main.asyncAfter(deadline: .now() + 3) {<br>        toastController.dismiss(<br>            animated: true,<br>            completion: nil<br>        )<br>      }<br>        <br>      pluginResult = CDVPluginResult(<br>        status: CDVCommandStatus_OK,<br>        messageAs: msg<br>      )<br>    }<br><br>    self.commandDelegate!.send(<br>      pluginResult,<br>      callbackId: command.callbackId<br>    )<br>  }<br>    }<br><br>    </pre><p><strong>1. Imports and Class Definition:</strong></p><ul><li>@objc(CordovaHelloWorld) class CordovaHelloWorld: CDVPlugin { ... }: Defines an Objective-C class named CordovaHelloWorld that extends the CDVPlugin class, the base class for Cordova plugins on iOS.</li></ul><p><strong>2. </strong><strong>sayHello Method:</strong></p><ul><li>@objc func sayHello(_ command: CDVInvokedUrlCommand) { ... }: This method is called when JavaScript invokes the &quot;sayHello&quot; method from the plugin.</li><li>var pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR): Initializes a CDVPluginResult object to send a response back to JavaScript, initially set to an error status.</li></ul><p><strong>3. Handling Message and Displaying Alert:</strong></p><ul><li>let msg = command.arguments[0] as? String ?? &quot;&quot;: Retrieves the first argument passed from JavaScript (the message to display) and safely handles potential missing arguments.</li><li>if msg.characters.count &gt; 0 { ... }: If the message is not empty:</li><li>Creates a UIAlertController to display as a temporary alert.</li><li>Presents the alert controller on the main view controller.</li><li>Uses DispatchQueue.main.asyncAfter to dismiss the alert automatically after 3 seconds.</li><li>Updates the pluginResult to a success status with the message.</li></ul><p><strong>4. Sending Response to JavaScript:</strong></p><ul><li>self.commandDelegate!.send(pluginResult, callbackId: command.callbackId): Sends the pluginResult back to JavaScript, indicating success or error and potentially returning the message.</li></ul><h3>Create the package.json</h3><p>Here just run this command and Plugman will create it for you :)</p><pre>sudo plugman createpackagejson &quot;url to your plugin folder&quot;</pre><h3>Create the IONIC wrapper</h3><p>Now it&#39;s time to run our custom lib, to do this we gonna use the Awesome-Cordova-plugins repo, and clone it in your Desktop folder (for example).</p><pre>git clone https://github.com/danielsogl/awesome-cordova-plugins.git</pre><p>then run these commands, were “Cordova HelloWorld” is the name of the plugin</p><pre>sudo npm install<br>gulp plugin:create -m -n CordovaHelloWorld </pre><p>go to <em>awesome-cordova-plugins/src/@awesome-cordova-plugins/plugins </em>and search the folder that matches your plugin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X9Bm6FX9AZsoCHTf10y3sQ.png" /></figure><p>open the index.ts and edit it, the file is already well explained and documented, however, this is an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oMzlose_UUUbQ5VqMjy66g.png" /></figure><p>The next step is to build the Awesome-Cordova-plugins</p><pre>npm run build</pre><p>this will generate a folder <em>dist</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrpF3SrgV6C81aQiEyJNjg.png" /></figure><p>we just need to copy the folder of our plugin and paste it into the Awesome-Cordova-plugins in our project, With the image you will have a good reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*rxlfwzkJ8uNEFyqqVp9RuQ.png" /></figure><p>Naturally, this manual way is not the best for production, in a <strong>professional environment</strong>, this IONIC wrapper generation is made by a pipeline and added to the ionic-native automatically when we install the dependencies in IONIC, but that is another topic.</p><h3>Add your new plugin to the project</h3><pre>sudo ionic cordova plugin add &lt;path to the plugin&gt;</pre><p>add the plugin and declare the plugin in the AppModule</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*xcOcSqYIsSzOLfuR5vXqzA.png" /></figure><p>now you can use the plugin in any component !!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*R3W7fCWJgdCbJYBoyHoLBg.png" /><figcaption>import the plugin and inject it</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*JxiT4eEsbnFWvgtjVJrZ2g.png" /><figcaption>execute the plugin functions</figcaption></figure><h3>Test your new Cordova plugin</h3><p>Run your IONIC app <em>sudo ionic cordova run android or sudo ionic cordova run ios</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*2SbahaI6n8MvM91fWkk25w.png" /></figure><p>There it is, congratulations 👏 , you have created a new Cordova plugin.</p><p><strong>Thanks for reading I hope the article was enjoyable, useful and informative for you. You can reach me on </strong><a href="https://www.linkedin.com/in/kevin-alexander-penaranda-soto-kalex/"><strong>LinkedInd</strong></a><strong> and </strong><a href="https://www.youtube.com/channel/UCjkEHeqVIw2jBMT5ehOWuoQ"><strong>YouTube</strong></a><strong>. Do not forget to follow me and like the post.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4fdbedc5291" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Professional Android App Foundation]]></title>
            <link>https://kevinalexandersoto.medium.com/professional-android-app-foundation-f3ca84315462?source=rss-141c0eed32c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3ca84315462</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Kevin Alexander Soto]]></dc:creator>
            <pubDate>Thu, 31 Aug 2023 17:44:02 GMT</pubDate>
            <atom:updated>2023-08-31T17:44:02.027Z</atom:updated>
            <content:encoded><![CDATA[<p>This post gives you a list of things to do when you create a new Android app. This list is based on my experience as an Android developer. If you think that a professional app requires any additional features at the beginning, feel free to share your opinion in the comments.</p><h3><strong>Centralize the dependencies</strong></h3><p>Centralizing the dependencies means using a <a href="https://docs.gradle.org/current/userguide/platforms.html">version catalog</a> or another way to separate and share the dependencies of the app. By doing this, in the future, you don’t have to worry about updating version dependency by dependency or changing the version module by module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_mFN5-MEliXZXIQGGaaCQ.png" /></figure><h3>Add the more common dependencies and the possible future ones</h3><p>When creating a new Android app, there are some dependencies that are essential for the project, such as compose, a DI library, Retrofit (or another HTTP client), Room, an image loader, Coroutines, Material 3 or navigation. Additionally, it might be convenient to add project-specific dependencies, such as CameraX, FireBase, Epoxy, or other particular needs of the app. This will make the team’s work easier in the future.</p><h3>Add Build variants</h3><p>Define the debug, release, QA-specific variants, and if it’s possible the specific environments(like the backEnd endpoint).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aH2B6G4Eyue_11f0v60GaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*DvmgIJukvz0hUHS6betNDw.png" /></figure><h3>Set an output name for the APK or bundle app</h3><p>At the beginning of the development process may not be useful and if your team has a CI/CD process this will not have a big impact, but if you are in a small company could be probable that you have to send the APK to the QA or to some one else to see a demo of the application. Setting up the name for the output APK will help you and the team to identify the version and buildVariant of the App.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SKBZj9GFkoEnP1RLRkKC0Q.png" /></figure><h3>Configure Network security file</h3><p>This can help you customize and protect your app’s network communications. Some of the reasons to use this file are:</p><ul><li>Customize the Certificate Authorities (CA) that you trust for your app’s secure connections. For example, trust self-signed certificates or restrict the set of public CAs that you trust.</li><li>Override security settings only for debugging, without affecting your app’s installed base.</li><li>Opt out of cleartext (unencrypted) traffic, to protect your app from accidental usage of this type of traffic.</li><li>Pin certificates, to restrict your app’s secure connection to specific certificates.</li></ul><p><a href="https://developer.android.com/training/articles/security-config#manifest">Here </a>you can find more information and details on how to use this file.</p><h3>Set up the DI</h3><p>Libraries like Dagger Hilt require setting up the Application and adding other plugins, be sure that this is done.</p><h3>Accelerate the build process</h3><p>It is important to accelerate the build process in Android because this can improve the productivity and efficiency of the developers. A fast build process allows you to test and debug your code more easily, as well as implement changes and new features more frequently. Additionally, a fast build process reduces the waiting time and frustration of the developers and in some cases, the CI/CD pipeline build time for new artifacts which improves their experience and satisfaction. <a href="https://developer.android.com/build/optimize-your-build">Here </a>you can find more information about the configuration, the usual modification is to increase the JVM heap size and experiment with the JVM parallel garbage collector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yZYaxGEc-Hlrgs5-KW1eQ.png" /></figure><h3>Plan the app for modularization</h3><p>It is important to have a plan for the app modularization in Android because this can improve the maintainability and overall quality of the code. Modularization is a practice of organizing the code into independent and clear-purpose parts, called modules. <a href="https://developer.android.com/topic/modularization">Some of the benefits of modularization are1</a>:</p><ul><li>Reusability: Modularization enables code sharing and building multiple apps from the same foundation. Modules are building blocks. Apps should be a sum of their features, where the features are organized as separate modules.</li><li>Strict visibility control: Modules enable you to easily control what you expose to other parts of the code. You can mark everything but your public interface as internal or private to prevent it from being used outside the module.</li><li>Customizable delivery: Play Feature Delivery uses the advanced capabilities of app bundles, allowing you to deliver certain features of the app conditionally or on demand.</li><li>Scalability: In a tightly coupled codebase, a single change can trigger a cascade of alterations in seemingly unrelated parts of code. A properly modularized project will embrace the separation of concerns principle and therefore limit the coupling. This empowers the contributors through greater autonomy.</li><li>Ownership: In addition to enabling autonomy, modules can also be used to enforce accountability.</li></ul><p><a href="https://android-developers.googleblog.com/2022/09/announcing-new-guide-to-android-app-modularization.html">To see modularization in action, you can check out the Now in Android project2</a>. It’s a fully functional app that has a multi-module codebase, and there’s a handy learning journey on modularization that outlines what the modules do and how they communicate with each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YgLjYjWbEKK1cjq-W7DNKg.png" /></figure><p>I appreciate your time and attention to this article! If you enjoyed it, please show your support by clapping. I would love to hear from you on <a href="https://www.linkedin.com/in/kevin-alexander-penaranda-soto-kalex/">Linkedin </a>and <a href="https://twitter.com/Kalex_sr">Twitter</a>. You can also follow me and this publication for more interesting content. Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3ca84315462" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Room DB pagination without Paging - Android Jetpack Compose]]></title>
            <link>https://kevinalexandersoto.medium.com/room-db-pagination-without-paging-android-jetpack-compose-ade3c1b60dba?source=rss-141c0eed32c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ade3c1b60dba</guid>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[room-database]]></category>
            <dc:creator><![CDATA[Kevin Alexander Soto]]></dc:creator>
            <pubDate>Fri, 30 Jun 2023 00:16:33 GMT</pubDate>
            <atom:updated>2023-06-30T23:46:18.668Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*uXjErz2FoJi1RV7FGWvZuA.png" /></figure><h3><strong>Room DB pagination without Paging Android Jetpack Compose</strong></h3><p>Room DB is a popular library for working with SQLite databases in Android. One of the challenges of using Room DB is how to handle large datasets that cannot fit in memory or on the screen. This is where pagination comes in. In this post, we are going to add pagination to our Room DB without Paging library.</p><h3>Data</h3><p>I suppose that you already have a DB created and a basic implementation (The Entity, DAO, TypeConverter, etc ). So, I have an Interface NoteDao with some database interactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*tmdlb70snHWw3X2KUZHMpg.png" /><figcaption>My basic DAO interface</figcaption></figure><p>Here we are going to add another interaction to get the notes paginated.</p><pre>@Query(&quot;SELECT * FROM note WHERE subject_id == :id ORDER BY note_date DESC LIMIT :limit OFFSET :offset&quot;)<br>suspend fun getPagingNotesOrderByDate(id: Int, limit: Int, offset: Int): List&lt;Note&gt;</pre><p>This looks like a normal Room query impl, the special thing here is that we are using the <strong>LIMIT</strong> and <strong>OFFSET</strong> SQL clauses.</p><p>The <strong>LIMIT</strong> specifies the maximum number of rows that the query can return. The <strong>OFFSET</strong> clause specifies how many rows to skip before returning the result set. In this syntax, you need to use an <strong>ORDER BY</strong> clause to ensure the order of the rows in the result set.</p><p>This is all we have to do with our DB, the next step is to <strong>use our DAO</strong> in the Repository.</p><h3>Repository</h3><p>This is another simple peace of code.</p><pre>override suspend fun getPagingNotesByDate(subjectID: Int, limit: Int, offset: Int): List&lt;Note&gt; {<br>    return notesDao.getPagingNotesOrderByDate(subjectID, limit, offset)<br>}</pre><p>You can define Your own Repository and logic, mine are defined in this way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*SYy3tD8Y86_DTSIepE7kiQ.png" /></figure><p>This is all for our repo, the next step is adding the ViewModel to handle the pagination.</p><h3>ViewModel</h3><p>We can begin creating a simple ViewModel structure and an enum class to manage our paging state.</p><pre>@HiltViewModel<br>class PagingRecordsViewModel @Inject constructor(<br>    private val notesRepositoryImpl: NotesRepository,<br>    private val dispatcher: CoroutineDispatcher,<br>) : ViewModel() {<br><br>  <br>}</pre><pre>enum class PaginationState {<br>    REQUEST_INACTIVE,<br>    LOADING,<br>    PAGINATING,<br>    ERROR,<br>    PAGINATION_EXHAUST,<br>    EMPTY,<br>}</pre><p>The enum class PaginationState has six constants: REQUEST_INACTIVE, LOADING, PAGINATING, ERROR, PAGINATION_EXHAUST and EMPTY. These constants represent different states of a pagination process.</p><p><strong>REQUEST_INACTIVE</strong> : This state represents the end of a pagination request.</p><p><strong>LOADING</strong> : Represent the first Loading of the screen.</p><p><strong>PAGINATING</strong> : It is set when the pagination is loading.</p><p><strong>PAGINATION_EXHAUST</strong> : To represent the end of the pagination.</p><p><strong>EMPTY</strong> : This state is to set an Empty screen when the first loading result is empty.</p><p>Next, we gonna add some properties to handle the notes list and the paging state.</p><pre>private val _notesList =<br>    MutableStateFlow&lt;MutableList&lt;Note&gt;&gt;(mutableListOf())<br>val notesList: StateFlow&lt;List&lt;Note&gt;&gt;<br>    get() = _notesList.asStateFlow()</pre><p>The code defines two properties: _notesList and notesList. The first one is a <strong>MutableStateFlow</strong> of type MutableList&lt;Note&gt;, which means it can hold and update a mutable list of notes. The second one is a <strong>StateFlow</strong> of type List&lt;Note&gt;, which means it can only read the list of notes. <a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-state-flow/">The second property is initialized by calling the </a><a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-state-flow/">asStateFlow() extension function on the first property, which creates a read-only view of the mutable state flow2</a>.</p><p>The purpose of this code is to expose a public read-only state flow (notesList) from a private mutable state flow (_notesList). This way, the class that owns these properties can control how the state is updated, while other classes can only observe the state changes.</p><p>The same impl is for the pagingState property.</p><pre>private val _pagingState =<br>    MutableStateFlow&lt;PaginationState&gt;(PaginationState.LOADING)<br>val pagingState: StateFlow&lt;PaginationState&gt;<br>    get() = _pagingState.asStateFlow()</pre><p>We will need two more properties, one to “store” the current page and the other as a flag to paginate.</p><pre>private var page = 0<br>var canPaginate by mutableStateOf(false)</pre><p><strong>Checkpoint!!!</strong> This is how our ViewModel class looks so far.</p><pre>@HiltViewModel<br>class PagingRecordsViewModel @Inject constructor(<br>    private val notesRepositoryImpl: NotesRepository,<br>    private val dispatcher: CoroutineDispatcher,<br>) : ViewModel() {<br><br>    private val _notesList =<br>        MutableStateFlow&lt;MutableList&lt;Note&gt;&gt;(mutableListOf())<br>    val notesList: StateFlow&lt;List&lt;Note&gt;&gt;<br>        get() = _notesList.asStateFlow()<br><br>    private val _pagingState =<br>        MutableStateFlow&lt;PaginationState&gt;(PaginationState.LOADING)<br>    val pagingState: StateFlow&lt;PaginationState&gt;<br>        get() = _pagingState.asStateFlow()<br><br>    private var page = 0<br>    var canPaginate by mutableStateOf(false)<br><br><br>}</pre><p>The next step is to create a function to fetch the data, I will call it <em>getNote.</em></p><pre>fun getNotes(subjectID: Int) {<br>}</pre><p>Inside getNote, first of all, we are going to set the pagingState, at this point, it could be Loading or paginating.</p><pre>if (page == 0 || (canPaginate) &amp;&amp; _pagingState.value == PaginationState.REQUEST_INACTIVE) {<br>    _pagingState.update { if (page == 0) PaginationState.LOADING else PaginationState.PAGINATING }<br>}</pre><p>This piece of code is a conditional statement that checks if the following conditions are met:</p><ul><li>The <strong>page</strong> variable is equal to 0, which means the first page of data is requested, or</li><li>The <strong>page</strong> variable is not equal to 0, which means a subsequent page of data is requested, and the<strong> canPaginate</strong> variable is true, which means there are more pages available, and</li><li>The _pagingState property, which is a <strong>MutableStateFlow</strong> of type PaginationState, has a value of <strong>PaginationState.REQUEST_INACTIVE</strong>, which means there is no ongoing pagination request.</li></ul><p>If all these conditions are true, then the code updates the <strong>_pagingState</strong> property by assigning a new value to it. The new value depends on the page variable:</p><ul><li>If the page variable is equal to 0, then the new value is <strong>PaginationState.LOADING</strong>, which means the first page of data is being loaded.</li><li>If the page variable is not equal to 0, then the new value is <strong>PaginationState.PAGINATING</strong>, which means a subsequent page of data is being loaded.</li></ul><p>The purpose of this code is to control the pagination process and avoid making unnecessary or duplicate requests for data. It also updates the state of the pagination process so that other classes can observe it and react accordingly.</p><p>Next, let’s make the request to our DB, this request is async, which means we will execute it inside a coroutine and a try—catch sentence.</p><pre>viewModelScope.launch(dispatcher) {<br>    try {<br>        val result = notesRepositoryImpl.getPagingNotesByDate(subjectID, 5, page * 5)<br><br>    } catch (e: Exception) {<br>        _pagingState.update { if (page == 0) PaginationState.ERROR else PaginationState.PAGINATION_EXHAUST }<br>    }<br>}</pre><p>The code launches a coroutine using the dispatcher parameter, which specifies which thread or thread pool the coroutine should run on. In this case, the dispatcher should beDispatchers.IO, which means the coroutine will run on a thread that is optimized for Input-Output (IO) operations, like network requests or database queries.</p><p>The code then tries to execute a function called notesRepositoryImpl.getPagingNotesByDate, which returns a list of notes from a repository based on some parameters. The number 5 represents the page size of the Query and the last parameter is the <strong>OFFSET</strong>(explained in the first part of this article).</p><p>This next piece of code is executed after the function notesRepositoryImpl.getPagingNotesByDate .</p><pre>canPaginate = result.size == 5<br><br>if (page == 0) {<br>    if (result.isEmpty()) {<br>        _pagingState.update { PaginationState.EMPTY }<br>        return@launch<br>    }<br>    _notesList.value.clear()<br>    _notesList.value.addAll(result)<br>} else {<br>    _notesList.value.addAll(result)<br>}<br><br>_pagingState.update { PaginationState.REQUEST_INACTIVE }<br><br>if (canPaginate) {<br>    page++<br>}<br><br>if (!canPaginate) {<br>    _pagingState.update { PaginationState.PAGINATION_EXHAUST }<br>}</pre><p>It performs the following steps:</p><ul><li>It assigns a boolean value to a variable called canPaginate, which indicates whether there are more pages of data available. The value is true if the result list has 5 items, which is the maximum number of items per page, and false otherwise.</li><li>It checks if the page parameter is equal to 0, which means the first page of data was requested. If so, it performs the following sub-steps:<br><strong>-</strong> It checks if the result list is empty, which means there are no notes for the given subject ID. If so, it updates the _pagingState property to <strong>PaginationState.EMPTY</strong> and returns from the coroutine.<br><strong>-</strong> It clears the _notesList property, which is a <strong>MutableStateFlow</strong> of type MutableList&lt;Note&gt;, and adds all the items from the result list to it. This way, it replaces the previous list of notes with the new one.</li><li>It checks if the page parameter is not equal to 0, which means a subsequent page of data was requested. If so, it adds all the items from the result list to the _notesList property without clearing it. This way, it appends the new list of notes to the existing one.</li><li>It updates the _pagingState property to <strong>PaginationState.REQUEST_INACTIVE</strong>, which means there is no ongoing pagination request.</li><li>It checks if canPaginate is true, which means there are more pages of data available. If so, it increments the page variable by one, which means it prepares to request the next page of data.</li><li>It checks if canPaginate is false, which means there are no more pages of data available. If so, it updates the _pagingState property to <strong>PaginationState.PAGINATION_EXHAUST</strong>, which means there is no more data to load.</li></ul><p>The purpose of this code is to process the result of the IO operation and update the state and content of the pagination process accordingly. It also keeps track of the current page and whether there are more pages to request.</p><p>The last function of our ViewModel is to clear the previous state and content of the pagination process and start over from the first page.</p><pre>fun clearPaging() {<br>    page = 0<br>    _pagingState.update { PaginationState.LOADING }<br>    canPaginate = false<br>}</pre><p><strong>Note:</strong> we can refactor the ViewModel, setting some const to our page size and the initial page.</p><pre>companion object {<br>    const val PAGE_SIZE = 5<br>    const val INITIAL_PAGE = 0<br>}</pre><p><strong>Code snippet</strong> of the ViewModel.</p><pre>@HiltViewModel<br>class PagingRecordsViewModel @Inject constructor(<br>    private val notesRepositoryImpl: NotesRepository,<br>    private val dispatcher: CoroutineDispatcher,<br>) : ViewModel() {<br><br>    private val _notesList =<br>        MutableStateFlow&lt;MutableList&lt;Note&gt;&gt;(mutableListOf())<br>    val notesList: StateFlow&lt;List&lt;Note&gt;&gt;<br>        get() = _notesList.asStateFlow()<br><br>    private val _pagingState =<br>        MutableStateFlow&lt;PaginationState&gt;(PaginationState.LOADING)<br>    val pagingState: StateFlow&lt;PaginationState&gt;<br>        get() = _pagingState.asStateFlow()<br><br>    private var page = INITIAL_PAGE<br>    var canPaginate by mutableStateOf(false)<br><br>    fun getNotes(subjectID: Int) {<br>        if (page == INITIAL_PAGE || (page != INITIAL_PAGE &amp;&amp; canPaginate) &amp;&amp; _pagingState.value == PaginationState.REQUEST_INACTIVE) {<br>            _pagingState.update { if (page == INITIAL_PAGE) PaginationState.LOADING else PaginationState.PAGINATING }<br>        }<br>        viewModelScope.launch(dispatcher) {<br>            try {<br>                val result = notesRepositoryImpl.getPagingNotesByDate(subjectID, PAGE_SIZE, page * PAGE_SIZE)<br><br>                canPaginate = result.size == PAGE_SIZE<br><br>                if (page == INITIAL_PAGE) {<br>                    if (result.isEmpty()) {<br>                        _pagingState.update { PaginationState.EMPTY }<br>                        return@launch<br>                    }<br>                    _notesList.value.clear()<br>                    _notesList.value.addAll(result)<br>                } else {<br>                    _notesList.value.addAll(result)<br>                }<br><br>                _pagingState.update { PaginationState.REQUEST_INACTIVE }<br><br>                if (canPaginate) {<br>                    page++<br>                }<br><br>                if (!canPaginate) {<br>                    _pagingState.update { PaginationState.PAGINATION_EXHAUST }<br>                }<br>            } catch (e: Exception) {<br>                _pagingState.update { if (page == INITIAL_PAGE) PaginationState.ERROR else PaginationState.PAGINATION_EXHAUST }<br>            }<br>        }<br>    }<br><br>    fun clearPaging() {<br>        page = INITIAL_PAGE<br>        _pagingState.update { PaginationState.LOADING }<br>        canPaginate = false<br>    }<br><br>    companion object {<br>        const val PAGE_SIZE = 5<br>        const val INITIAL_PAGE = 0<br>    }<br>}</pre><p>This is all for the ViewModel, let’s go to the compose view.</p><h3>View</h3><p>First at all, we are going to inject the ViewModel using Hilt.</p><pre>pagingRecordsViewModel: PagingRecordsViewModel = hiltViewModel()</pre><p>Then we have to create some <strong>val</strong> state to manage the <strong>LazyColum </strong>state and the StateFlows from the ViewModel.</p><pre>val lazyColumnListState = rememberLazyListState()<br>val coroutineScope = rememberCoroutineScope()<br><br>val noteList = pagingRecordsViewModel.notesList.collectAsStateWithLifecycle()<br>val pagingState = pagingRecordsViewModel.pagingState.collectAsStateWithLifecycle()</pre><p>The <strong>rememberLazyListState</strong> function is a helper function that creates and remembers a LazyListState object across recompositions, so that the scroll position and other state information are preserved.</p><p>The <strong>collectAsStateWithLifecycle</strong> function is an extension function that collects the flow as a <strong>State&lt;T&gt;</strong> object that can be observed by the composable function, and also manages the lifecycle of the flow, so that it is only collected when the composable function is active.</p><p>Here we are making the first request to the DB and it only happens when the composable is compose the first time.</p><pre>LaunchedEffect(key1 = Unit) {<br>    pagingRecordsViewModel.clearPaging()<br>    pagingRecordsViewModel.getNotes(subjectId)<br>}</pre><p>The <strong>LaunchedEffect</strong> function is useful when you want to perform some actions that are tied to the lifecycle of the composable, such as fetching data, showing a snackbar, or navigating to another screen.</p><p>Next, let’s add some logic to know when to paginate.</p><pre>val shouldPaginate = remember {<br>    derivedStateOf {<br>        pagingRecordsViewModel.canPaginate &amp;&amp; (<br>            lazyColumnListState.layoutInfo.visibleItemsInfo.lastOrNull()?.index<br>                ?: -5<br>            ) &gt;= (lazyColumnListState.layoutInfo.totalItemsCount - 3)<br>    }<br>}<br><br>LaunchedEffect(key1 = shouldPaginate.value) {<br>    if (shouldPaginate.value &amp;&amp; pagingState.value == PaginationState.REQUEST_INACTIVE) {<br>        pagingRecordsViewModel.getNotes(subjectId)<br>    }<br>}</pre><p>The value is calculated by using the <strong>derivedStateOf</strong> function, which is a way to create a state object that depends on other state objects. In this case, the value depends on three state objects: <strong>.canPaginate</strong>,<strong>lazyColumnListState.layoutInfo.visibleItemsInfo.lastOrNull()?.index</strong>, and <strong>lazyColumnListState.layoutInfo.totalItemsCount</strong>. The value is true if the app can paginate and the last visible item index is close to the total items count, meaning that the user has scrolled near the end of the list. The value is false otherwise. The <strong>derivedStateOf</strong> function ensures that the value only changes when the conditions change, and not when the state objects change for other reasons. The derivedStateOf helps us to improve the performance of our composable.</p><p>Then we have our <strong>LazyColumn</strong>, this is where we are going to show our Item list.</p><pre>LazyColumn(<br>    state = lazyColumnListState,<br>    horizontalAlignment = Alignment.CenterHorizontally,<br>    modifier = Modifier.padding(paddingValues),<br>) {<br>    items(<br>        noteList.value.size,<br>        key = { noteList.value[it].noteId },<br>    ) {<br>        RecordItem(<br>            noteList.value[it].imgUrl.decodeUri(),<br>            recordDescription = noteList.value[it].noteDescription,<br>            onRecordClick = { onRecordDetail(noteList.value[it].noteId) },<br>            onDeleteRecord = {<br>               <br>            },<br>        )<br>    }</pre><p>Do not forget to add<strong> lazyColumnListState</strong> to the state of the <strong>LazyColumn. </strong>Finally, we can add a <strong>when</strong> expression to listen to our <strong>pagingState.value</strong> and add new Items according to the state, like we do with the paging3 library.</p><pre>when (pagingState.value) {<br>    PaginationState.REQUEST_INACTIVE -&gt; {<br>    }<br><br>    PaginationState.LOADING -&gt; {<br>        item {<br>            BYLoadingIndicator()<br>        }<br>    }<br><br>    PaginationState.PAGINATING -&gt; {<br>        item {<br>            BYLoadingIndicator()<br>        }<br>    }<br><br>    PaginationState.ERROR -&gt; TODO()<br>    PaginationState.PAGINATION_EXHAUST -&gt; {<br>        item {<br>            Column(<br>                modifier = Modifier.fillMaxHeight().padding(8.dp),<br>            ) {<br>                Text(text = stringResource(id = R.string.record_list_end_text))<br>            }<br>        }<br>    }<br><br>    PaginationState.EMPTY -&gt; {<br>        item {<br>            EmptyScreen(<br>                onAddItemClick = { onAddNewRecord.invoke() },<br>                rationaleText = R.string.records_list_no_recordsFount_text,<br>            )<br>        }<br>    }<br>}</pre><p>The result :)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FoKByHjGAVQs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DoKByHjGAVQs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FoKByHjGAVQs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaea3c0d65d2e5c8af3fc7c2c294d011/href">https://medium.com/media/eaea3c0d65d2e5c8af3fc7c2c294d011/href</a></iframe><p><strong>Note:</strong> It is probable that you could not saw the loading indicator, that is because the data is loaded fast from the DB, to see the loading indicator for design purpose, use a delay in the repository.</p><h3>Last Notes</h3><p>This is my first article here in Medium, I hope the article was enjoyable<strong>, </strong>useful and informative for you. You can reach me on <a href="https://www.linkedin.com/in/kevin-alexander-penaranda-soto-kalex/">LinkedInd</a> and <a href="https://www.youtube.com/channel/UCjkEHeqVIw2jBMT5ehOWuoQ">YouTube</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ade3c1b60dba" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>