<?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 Marelso on Medium]]></title>
        <description><![CDATA[Stories by Marelso on Medium]]></description>
        <link>https://medium.com/@marelso?source=rss-399a3ae568ba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*h5XCkQG8sJ-E3QwWt4BV5Q.jpeg</url>
            <title>Stories by Marelso on Medium</title>
            <link>https://medium.com/@marelso?source=rss-399a3ae568ba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 10:52:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marelso/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[Running AI models locally with Kotlin]]></title>
            <link>https://medium.com/@marelso/running-ai-models-locally-with-kotlin-88201c568928?source=rss-399a3ae568ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/88201c568928</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[tinyllama]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Marelso]]></dc:creator>
            <pubDate>Wed, 09 Sep 2026 23:48:05 GMT</pubDate>
            <atom:updated>2026-09-09T23:48:05.138Z</atom:updated>
            <content:encoded><![CDATA[<p>Performing Inference Using Llamatik</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*VQjiwUcL5e3veKdPh24L0Q.png" /></figure><p>In recent years, several language models have emerged in the artificial intelligence landscape. Companies like OpenAI, Anthropic, and Google have proven their value with robust models and high efficiency. However, along with the rise of these models, a cloud dependent business model has become firmly established.</p><p>By adopting this format, we take on risks and costs that can be decisive for a project’s sustainability. Although cloud models eliminate upfront infrastructure costs and are frequently updated, they bring variable operational costs, require a continuous internet connection, and also subject your application’s data to network traffic.</p><p>With these issues in mind, models focused on local execution have emerged. They are designed to run on your own servers or, in many cases, directly on the end user’s device. Since they are not dependent on network connections, these models carry a higher risk of technical obsolescence, transferring to you the responsibility for updates, security patches, and even hardware failures. On the flip side, they compensate with full control over data and fixed, predictable costs, making them ideal for offline or niche applications whose data does not change frequently.</p><p>In this article, we will briefly go over some fundamental artificial intelligence concepts, but the main focus will be on implementing these language models in Kotlin applications with Jetpack Compose.</p><h3><strong>A brief context on AI</strong></h3><h4><strong>What is Inference?</strong></h4><p>Inference is the phase in which an artificial intelligence model puts into practice all the knowledge acquired during its training. While training is a slow process that requires intense computational power, inference is the fast and efficient execution of the model.</p><blockquote>You can find more details about inference <a href="https://cloud.google.com/discover/what-is-ai-inference">here</a>.</blockquote><h4><strong>What are GGUF Files?</strong></h4><p>The GGUF (GPT-Generated Unified Format) is one of the key factors making local inference for large language models viable. It stores these models in a compact and efficient way so they can be loaded and executed quickly on common hardware. This solves a crucial problem for local execution: language models are heavy, which makes their use unfeasible on less powerful devices that are often more common among users.</p><p>This format drastically reduces the size of these models through a process called quantization. Quantization is a technique to reduce the computational and memory costs of inference execution by representing weights and activations with low-precision data types, such as 8-bit integers (int8) instead of the usual 32-bit floating-point standard (float32).</p><p>The reduction in the number of bits means the resulting model requires less storage space and consumes less energy (in theory), while also allowing operations like matrix multiplication to be performed much faster through integer arithmetic. This also enables the execution of models on embedded devices, which sometimes support only integer data types.</p><blockquote>Learn more about GGUF <a href="https://huggingface.co/docs/hub/gguf">here</a> and quantization <a href="https://huggingface.co/docs/optimum/concept_guides/quantization">here</a>.</blockquote><h4>What is the KV Cache</h4><p>When a model processes a prompt, it generates keys and values for each token. For a multi-turn conversation, re-processing the entire chat history from scratch for every new user question is wasteful.</p><p>KV cache reuse solves this. Instead of rebuilding the full prompt state each turn, the model “remembers” the processed history. It only needs to process the <em>new</em> tokens, which makes subsequent turns significantly faster.</p><blockquote>Learn more about KV cache <a href="https://huggingface.co/blog/not-lain/kv-caching">here</a></blockquote><h4><strong>What is Llamatik?</strong></h4><p>Llamatik is an open-source library responsible for integrating llama.cpp’s functionality into the Kotlin ecosystem, enabling language models to run independently. This provides developers with a private, cross-platform and high-performance alternative.</p><p>Its philosophy is simple: no prompts sent to external servers, no need for API keys, and certainly no per token costs. All inference happens locally, making it ideal for privacy focused applications, those serving specific niches, or ones that need to work in offline scenarios.</p><p>One of Llamatik’s qualities is that it is not merely a wrapper around llama.cpp. The library offers features that cover various needs to make the application truly independent of external resources. The API covers capabilities ranging from text generation and audio transcription to image generation and analysis, also including concurrent session management.</p><blockquote>Check out the full list of features <a href="https://github.com/ferranpons/Llamatik/blob/main/README.md#-features">here</a>.</blockquote><h4>What will we build?</h4><p>We will demonstrate the implementation of local language models by developing an application using Kotlin Multiplatform.</p><p>The app will have a simple goal: suggest songs according to what the user requests, as well as recommend research topics related to the user’s interests all running locally, without relying on the cloud.</p><p>You’ll see in practice how to load a GGUF model, configure Llamatik, and build a fluid chat interface that keeps user data 100% private.</p><p>We won’t focus on model development and training. For study purposes, I’ll be using a version of TinyLlama, which is a compact open-source model that is focused in generic purposes requests. You can find the model <a href="https://huggingface.co/TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF">here</a> or download directly via the terminal using the command below.</p><pre>wget https://huggingface.co/TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF/resolve/main/tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf</pre><p>The first step to implementing our model in the project is to add the GGUF file to the project directories. Since I’m only working with desktop, I’ll add a new package called &quot;models&quot; at the root of the desktop module. If you’re using Android, you can include the GGUF file inside an assets folder.</p><p>After copying the file to the project, this is the current folder structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*cK3F2iEA8FpEL4TAz1wVkg.png" /></figure><p>Now that we have the model loaded into the project, we can begin implementation. To do this, add the LlamaKit library to your build.gradle:</p><pre>implementation(&quot;com.llamatik:library:1.10.1&quot;)</pre><p>To isolate the responsibilities of interpreting the LlamaKit library, I’ll create a new class (which will be called LlamaAPIBridge). This class will be responsible for handling requests to the model and processing responses.</p><p>The first method we’ll develop in this class will be inside the initialization method. We’ll call the initGenerateModel method, which returns a Boolean indicating whether the model was loaded successfully. We&#39;ll call this method inside a check() block, which will be responsible for throwing an exception if the model cannot be loaded.</p><pre>init {<br>  check(LlamaBridge.initGenerateModel(&quot;models/tinyllama.gguf&quot;)) {<br>    &quot;Failed to initialize LlamaBridge&quot;<br>  }<br>}</pre><p>Once we’ve successfully loaded the model, we can start making requests.</p><p>The first method I’ll create for this project will be requesting music genres using the generate() method from LlamaBridge. This method requires a single prompt. Below is the prompt I&#39;ll be using:</p><p>“You are a data output bot. Your responses must be only a list. Never include explanations, greetings, or extra text. Generate a list of 20 music genres. Output only a list of genres. Do not include any other text.”</p><p>The model’s response should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*rkvRCM1Qt1Vi1_jpAGLi1w.png" /></figure><p>In the method, I will also handle the numbering removal and filter out lengthy genres:</p><pre>suspend fun getSuggestionsChips():List&lt;String&gt;=withContext(Dispatchers.IO){<br>  val response = LlamaBridge.generate(prompt)<br><br>  println(&quot;Response: \n$response&quot;)<br><br>  response.substringAfterLast(&#39;:&#39;)<br>    .lines()<br>    .asSequence()<br>    .filter { it.isNotBlank() }<br>    .map { it.substringAfter(&#39; &#39;) }<br>    .distinct()<br>    .filter { it.length &lt; 15 }<br>    .take(5)<br>    .toList()<br>}</pre><p>The screen will display these topics. When a user clicks on a topic, that genre will be sent to the model as a prompt so it can respond with the song recommendations for that genre.</p><p>For this approach I will be using generateWithContext() method with the following prompts:</p><blockquote>System prompt:<br>“You are a data output bot. Your responses must be only a list. Never include explanations, greetings, or extra text. Generate a list of 5 suggestions. Output only a list of songs. Do not include any other text.”</blockquote><blockquote>User prompt:<br>“Based on this request: ‘[$query]’, return only a list of songs. Dont include any note.”</blockquote><p>This is the complete method</p><pre>suspend fun getSuggestions(query: String): List&lt;String&gt; = withContext(Dispatchers.IO) {<br>  val response = LlamaBridge.generateWithContext(<br>    systemPrompt = systemPrompt,<br>    contextBlock = &quot;&quot;,<br>    userPrompt = userPrompt<br>  )<br><br>  println(&quot;Response: \n$response&quot;)<br><br>  response.substringAfterLast(&#39;:&#39;)<br>    .lines()<br>    .asSequence()<br>    .filter { it.isNotBlank() }<br>    .map { it.substringAfter(&#39; &#39;) }<br>    .distinct()<br>    .take(5)<br>    .toList()<br>}</pre><p>For this request the model’s response should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*45zwkx9nKiSN0gdA2iPmRg.png" /></figure><p>Notice that there is a bit of a mix-up information in the recommendations with the model hallucinating, merging information between distinct music titles and/or authors. That is the downside of using a general purpose model in specific scenarios.</p><p>We might be able to solve this issue by passing a refined context that the model can read, or even by changing the model to one that is more music focused.</p><p>By using a dedicated contextBlock, you avoid the performance degradation of the prompts and allow the model to anchor on the most relevant information. Passing this context I was able to reach the following results:</p><blockquote>MUSIC KNOWLEDGE DATABASE:<br> ROCK: Led Zeppelin (Stairway to Heaven, Whole Lotta Love), Queen (Bohemian Rhapsody, We Will Rock You), The Beatles (Hey Jude, Let It Be), AC/DC (Back in Black, Highway to Hell), Nirvana (Smells Like Teen Spirit, Come As You Are)<br> JAZZ: Miles Davis (So What, Kind of Blue), John Coltrane (My Favorite Things, Giant Steps), Louis Armstrong (What a Wonderful World, La Vie En Rose), Duke Ellington (Take the A Train, Mood Indigo)<br> CLASSICAL: Beethoven (Für Elise, Moonlight Sonata), Mozart (Eine Kleine Nachtmusik, Requiem), Bach (Toccata and Fugue, Air on the G String), Vivaldi (Four Seasons, Gloria)<br> HIP HOP: Tupac (California Love, Changes), Notorious B.I.G. (Juicy, Big Poppa), Eminem (Lose Yourself, Stan), Kendrick Lamar (HUMBLE., Alright)<br> ELECTRONIC: Daft Punk (Around the World, One More Time), The Chemical Brothers (Hey Boy Hey Girl, Galvanize), Kraftwerk (Autobahn, The Model), Aphex Twin (Windowlicker, Come to Daddy)<br> POP: Michael Jackson (Billie Jean, Thriller), Madonna (Like a Prayer, Vogue), Taylor Swift (Shake It Off, Blank Space), Adele (Rolling in the Deep, Someone Like You)<br> BLUES: B.B. King (The Thrill is Gone, Lucille), Robert Johnson (Cross Road Blues, Sweet Home Chicago), Muddy Waters (Hoochie Coochie Man, Mannish Boy), Eric Clapton (Layla, Tears in Heaven)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*Sw7iBpzF4i3J0kHjGH1DLA.png" /></figure><p>When the model was given a structured database to search for recommendations it intelligently distributed its selections across artists, songs, and get a diverse yet coherent list that showcased different dimensions of the genre.</p><p>The context block doesn’t just feed the model raw data, it provides clean anchors that allow the model to prioritize with precision. This leads to outputs that are both faithful to the provided information and thoughtfully reasoned.</p><h4>Handling user session</h4><p>Session management in Llamatik is a critical feature that enables KV cache persistence across requests. This means that, instead of rebuilding the entire prompt state from scratch for each new user request we can continue from where the model has already processed even after an app restart. This capability is particularly valuable for long-running conversations where users expect continuity across sessions.</p><p>In order to implement this we need to make a few changes in our code. I’ll add a Boolean property isContinuation that indicates whether we&#39;re resuming an existing session. During class initialization, immediately after model initialization, we&#39;ll call LlamaBridge.sessionLoad(path) and assign its return value to isContinuation.</p><p>Then, inside our getSuggestions(query: String) method we’ll check isContinuation before invoking generateWithContext(). If true, we&#39;ll call generateContinue() instead, which uses the cached context; otherwise, we start a new session.</p><p>On the other hand, for session persistence, we’ll add a companion method that calls LlamaBridge.sessionSave() with a session file path</p><pre>companion object {<br>  private val session = &quot;session/chat.session&quot;<br><br>  fun onClose() {<br>    LlamaBridge.sessionSave(session)<br>  }<br>}</pre><p>We’ll invoke this method in the window’s onCloseRequest() handler to ensure sessions are saved before the application exits</p><pre>private fun ApplicationScope.onCloseRequest() {<br>  LlamaAPIBridge.onClose()<br><br>  exitApplication()<br>}</pre><h4>Final thoughts</h4><p>In summary, the model demonstrated a clear contrast in performance depending on the nature of the request. When asked to suggest categories like music genres, it produced coherent and well structured results, indicating its ability to organize information logically. However, when tasked with specific data (in this case song recommendations) without additional context or clear constraints, the model exhibited a tendency to mix information.</p><p>This highlights a fundamental limitation of language models. While they excel at high level categorization and general knowledge tasks, they struggle with precision and factual accuracy when asked for specific details without explicit grounding. The solution lies in providing structured context blocks that anchor the model’s generation, ensuring outputs remain faithful to the provided information rather than relying on the model judgment.</p><p>By using session management we can preserve the context prompt engineering to mitigate most of these limitations turning the model from a creative generator into a reliable, context aware assistant.</p><p>This article was a brief introduction for AI and its applications. There’s a lot of improvements that can be made but I hope you found it helpful!</p><h3>References and resources</h3><ol><li><a href="https://cloud.google.com/discover/what-is-ai-inference">What is inference</a></li><li><a href="https://huggingface.co/docs/hub/gguf">GGUF file format</a></li><li><a href="https://huggingface.co/docs/optimum/concept_guides/quantization">What is quantization</a></li><li><a href="https://huggingface.co/blog/not-lain/kv-caching">What is KV Cache</a></li><li><a href="https://docs.llamatik.com/">Llamatik documentation</a></li><li><a href="https://github.com/marelso/llamatik-agent">Project repository</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88201c568928" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firebase for devs | Implementing push notifications]]></title>
            <link>https://medium.com/@marelso/firebase-for-devs-implementing-push-notifications-1fbd1cd761ca?source=rss-399a3ae568ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fbd1cd761ca</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Marelso]]></dc:creator>
            <pubDate>Mon, 13 Oct 2025 12:14:14 GMT</pubDate>
            <atom:updated>2025-10-14T07:15:43.737Z</atom:updated>
            <content:encoded><![CDATA[<p>Guide to sending notifications from backend to mobile apps</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wuj2tKkx6ygzyIYe68jM_g.jpeg" /></figure><p>When you wake up, you likely reach for your phone out of habit. The first thing you see is probably a couple of messages keeping you updated about things that happened while you were sleeping, such as unread messages, pending payments or coming promotions from a store.</p><p>These messages are known as push notifications. They can be sent directly from the backend or through firebase console to keep users informed, engaged, and even remind them of important events on their schedule.</p><h4>How does notifications affect software?</h4><p>When it comes to modern applications push notifications can be a critical feature as they act directly breaking the communication gap between users and the app. They are mostly used to: provide real time information (when you receive a payment), enhance engagement (like YouTube using notifications to announcing videos getting users attention by pausing their activities to interact with the app) and drive specific actions (like encouraging you to reply to a message or tweet).</p><p>However! There are some bad practices when working with notifications as well. Since they interact directly with the users, sending excessive or frequent notifications, too generic or irrelevant messages are likely to be annoying and cause users to reject the app.</p><h4>How does Firebase Cloud Messaging (FCM) work?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r0cDVHLp5WwmFXVO.png" /></figure><p>The FCM is a cross-platform service that works with both Android, iOS and Web simplifying the notification delivery. It acts as an abstraction layer between the application servers and user’s devices, handling all the complexities across distinct platforms/operational systems leaving the server and clients focusing on the business logic reducing development effort.</p><p>That also means that Firebase doesn’t interact directly with your device, Instead the backend builds and sends the message to FCM according to a specific token, which routes it to the appropriate platform service, such as Google Play Services for Android, and relies on the APIs available in each platform to deliver these messages back to the device via the SDK, which processes notifications or data payloads.</p><blockquote>Lean more about the FCM architecture <a href="https://firebase.google.com/docs/cloud-messaging/fcm-architecture">here</a></blockquote><h4>What will we build?</h4><p>In this article we will focus on implementing push notifications by building an API responsible for save and send these notifications to our users. This will act as a centralized server for managing notification data and delivering them to our user base. With this approach allow us to focus on actual implementation and, also, make possible to be used by any external API (like the one <a href="https://medium.com/@marelso/real-time-data-with-server-sent-events-9d174b475567">developed at this article</a>), as long as they share the same user base, to trigger the notifications according specific actions or events.</p><p>To achieve this we need a couple projects:</p><ul><li>The notification API built in Kotlin + Spring Boot</li><li>The client (external API) responsible to trigger this messages</li><li>The mobile app that will receive the messages</li></ul><blockquote>You can use the same <a href="https://bitbucket.org/marelso/workspace/projects/SCHED">project</a> that I am using or build your own</blockquote><h4>Getting started</h4><p>If you don&#39;t have a firebase account yet you can follow <a href="https://youtu.be/45w34u6nH_4">these</a> steps to create a account we&#39;ll follow <a href="https://firebase.google.com/docs/cloud-messaging/android/first-message">this documentation</a> to set our android app.</p><p>After properly configuring the android app the next thing we need to do is set up a service account for Firebase Admin SDK in the firebase console.</p><ol><li>Go to project settings</li><li>Service accounts</li><li>Then generate a new private key with the Firebase Admin SDK selected.</li></ol><blockquote>You can also follow this url by changing <strong>{project}</strong> to your actual project:<br><a href="http://console.firebase.google.com/project/%7Bproject%7D/settings/serviceaccounts/adminsdk">console.firebase.google.com/project/<strong>{project}</strong>/settings/serviceaccounts/adminsdk</a></blockquote><p>Now we need to add the Firebase&#39;s SDK dependency to our build.gradle</p><pre>implementation(&quot;com.google.firebase:firebase-admin:9.6.0&quot;)</pre><p>Then we need to include the generated key to our API. I am using it in Spring&#39;s resources package as <strong><em>adminsdk-service-account.json</em></strong><em> </em>and read it&#39;s content at a new configuration bean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*b84Xdhvi6GwOMYN6T1nX1g.png" /></figure><pre>@Configuration<br>class FirebaseConfig {<br>  @PostConstruct<br>  fun initialize() {<br>    try {<br>      val serviceAccount = javaClass<br>              .getResourceAsStream(&quot;/adminsdk-service-account.json&quot;)<br>      val options = FirebaseOptions.builder()<br>              .setCredentials(GoogleCredentials.fromStream(serviceAccount))<br>              .build()<br><br>      if (FirebaseApp.getApps().isEmpty()) {<br>        FirebaseApp.initializeApp(options)<br>      }<br>    } catch (e: IOException) {<br>      e.printStackTrace()<br>    }<br>  }<br>}</pre><h4>How the FCM token work?</h4><p>Tokens are unique identifiers generated by the FCM SDK for each client app instance. That means that tokens are tied to the device that user is using to access the application and not directly to the user. So, users with multiple devices (e.g., Android and web, or two Android devices) will have distinct tokens for each instance.</p><p>FCM SDK grants a new token when the application is installed and the SDK initializes for the first time on the given device. Be aware that these tokens can be refreshed or even revoked due to specific conditions. So they aren&#39;t guaranteed to remain the same forever and invalid tokens must be addressed to new and valid ones to ensure reliable messaging.</p><h4>Conditions that can make a token refresh or be invalidated</h4><ol><li><strong><em>App Reinstallation</em></strong>: reinstalling the app creates a new instance, that will receive a new token upon SDK initialization.</li><li><strong><em>Clearing Data/Caches</em></strong>: clearing the app data and cache it will reset the instance and a new token will be granted for that instance.</li><li><strong><em>Platform-Specific Events</em></strong>: some platforms might have events that will invalidate tokens. For Android, when stale tokens reach 270 days of inactivity, FCM considers them expired. However, a new token will be granted when the device connects again and the app is opened.</li></ol><blockquote>Lean more about managing tokens <a href="https://firebase.google.com/docs/cloud-messaging/manage-tokens">here</a></blockquote><h4>Registering mobile device&#39;s token</h4><p>With both android app configured and the API using Firebase Admin SDK set up, we can now access the <strong><em>FirebaseMessaging</em></strong> class and perform the operations that we need. This class is used in mobile apps to manage the tokens necessary to publish notifications by the backend. I will start by adding a new Controller, Service and Repository to save our account&#39;s tokens. I will focus on the mobile-side code since the backend envolves standard CRUD operations and not related with our implementation but you can find the code here (<a href="https://bitbucket.org/marelso/notifications-back/src/main/src/main/kotlin/io/marelso/notifications/controller/AccountController.kt">controller</a>, <a href="https://bitbucket.org/marelso/notifications-back/src/main/src/main/kotlin/io/marelso/notifications/service/AccountService.kt">service</a>, <a href="https://bitbucket.org/marelso/notifications-back/src/main/src/main/kotlin/io/marelso/notifications/repository/AccountRepository.kt">repository</a>, <a href="https://bitbucket.org/marelso/notifications-back/src/main/src/main/kotlin/io/marelso/notifications/domain/Account.kt">model</a>).</p><p>We can register our mobile&#39;s app token by reaching the POST method at accounts controller. To do this, we can add a new class that extends <strong><em>FirebaseMessagingService</em></strong> and add it to our android&#39;s manifest.</p><p>Our user&#39;s device token will be available at app start and we can access it at <strong><em>onNewToken</em></strong> method to send it to our API. If your app uses Lazy Registration you might check if your user is logged in before saving it (or distinct the tokens from logged users).</p><pre>class MessagingService: FirebaseMessagingService() {<br>  private val repository: NotificationRepository by inject()<br><br>  companion object {<br>    const val TAG = &quot;FirebaseMessagingService&quot;<br>  }<br><br>  override fun onNewToken(token: String) {<br>    Log.d(TAG, &quot;Refreshed token: $token&quot;)<br><br>    CoroutineScope(Dispatchers.IO).launch {<br>      try {<br>        val result = repository.post(token)<br>  <br>        if(result.isSuccessful) {<br>          Log.d(TAG, &quot;Successfully send token: $token.&quot;)<br>        } else {<br>          Log.d(TAG, &quot;Error while send token: $token. ${result.message()}&quot;)<br>        }<br>      } catch (ex: Exception) {<br>        Log.d(TAG, &quot;Error while send token: $token. ${ex.message}&quot;)<br>      }<br>    }<br>    super.onNewToken(token)<br>  }<br><br>  override fun onMessageReceived(message: RemoteMessage) {<br>    if (message.data.isNotEmpty()) {<br>      Log.d(TAG, &quot;Message Data payload: &quot; + message.data)<br>    }<br>    super.onMessageReceived(message)<br>  }<br>}</pre><pre>&lt;service<br>    android:name=&quot;.data.MessagingService&quot;<br>    android:exported=&quot;false&quot;&gt;<br>    &lt;intent-filter&gt;<br>        &lt;action android:name=&quot;com.google.firebase.MESSAGING_EVENT&quot;/&gt;<br>    &lt;/intent-filter&gt;<br>&lt;/service&gt;</pre><p>You can also access the token at any point of your code by using the following snippet:</p><pre>CoroutineScope(Dispatchers.IO).launch {<br>  val token = Firebase.messaging.token.await()<br>  try {<br>    val result = repository.post(token)<br><br>    if(result.isSuccessful) {<br>      Log.d(TAG, &quot;Successfully send token: $token.&quot;)<br>    } else {<br>      Log.d(TAG, &quot;Error while send token: $token. ${result.message()}&quot;)<br>    }<br>  } catch (ex: Exception) {<br>    Log.d(TAG, &quot;Error while send token: $token. ${ex.message}&quot;)<br>  }<br>}</pre><blockquote>Check more about managing the token <a href="https://firebase.google.com/docs/cloud-messaging/manage-tokens">here</a></blockquote><p>Also, don&#39;t forget to add notification related permissions at the manifest depending on the android&#39;s version your app is targeting.</p><pre>&lt;uses-permission android:name=&quot;android.permission.POST_NOTIFICATIONS&quot; /&gt;</pre><h4>Notifying users</h4><p>In order to notify our users from external event, we&#39;ll add a new endpoint to our API. This endpoint will receive a <strong><em>SendNotification</em></strong> model containing the message title and body.</p><pre>data class SendNotification(<br>  val title: String,<br>  val body: String<br>)</pre><p>In my case I will send the notifications to all registered users in my database, but you can include a segmentation approach by including the specific tokens or rules to get them as one of the endpoint’s parameters as well. The best approach would be having the token as one of Account properties but here I think we can abstract the account interaction.</p><p>At our service I&#39;ve created a new method <strong><em>saveAndSendNotification</em></strong> that receive the <strong><em>SendNotification</em></strong> model and save at our database the new notification and, then, after saving the notification record it triggers the method that will delivery it to our users.</p><pre>fun saveAndSendNotification(notification: SendNotification): Notification {<br>  return save(notification).apply {<br>    send(this, accountTokens())<br>  }<br>}<br><br>private fun save(notification: SendNotification): Notification {<br>  return repository.save(NotificationFactory.from(notification))<br>}<br><br>private fun send(notification: Notification, tokens: List&lt;String&gt;) {<br>  tokens.forEach { token -&gt;<br>    try {<br>      send(notification, token)<br>    } catch (e: Exception) {<br>      e.printStackTrace()<br>      return@forEach<br>    }<br>  }<br>}<br><br>private fun send(notification: Notification, token: String) {<br>  FirebaseMessaging.getInstance().send(<br>    Message.builder()<br>      .setToken(token)<br>      .setNotification(<br>        com.google.firebase.messaging.Notification.builder()<br>          .setTitle(notification.title)<br>          .setBody(notification.description)<br>          .build()<br>      )<br>    .build()<br>  )<br>}</pre><p>Now our notification API is fully implemented and ready to receive requests and dispatch those notifications for our users! At this point you can test the end-to-end messaging flow from the API to mobile devices by using swagger.</p><blockquote>By default you can access by <a href="http://localhost:8081/swagger-ui/index.html">http://localhost:8081/swagger-ui/index.html</a></blockquote><p>For this project I will implement the post request at Schedule API device’s delete flow using feign. We’ll start by adding the latest version at build.gradle and enabling it at Application file:</p><pre>implementation(&quot;org.springframework.cloud:spring-cloud-starter-openfeign:4.3.0&quot;)</pre><pre>@SpringBootApplication<br>@EnableFeignClients<br>class ScheduleApplication<br>fun main(args: Array&lt;String&gt;) {<br>    runApplication&lt;ScheduleApplication&gt;(*args)<br>}</pre><p>Then we can create a new class and service that will handle the post request to our Notification API.</p><pre>@FeignClient(<br>    name = &quot;NotificationClient&quot;,<br>    url = &quot;\${notification.url}&quot;<br>)<br>interface NotificationClient {<br>    @PostMapping(&quot;/api/v1/notifications&quot;)<br>    fun sendNotification(@RequestBody notification: Notification)<br>}</pre><pre>@Service<br>class NotificationService(private val client: NotificationClient) {<br>    fun notify(notification: Notification) {<br>        client.sendNotification(notification)<br>    }<br>}</pre><p>And then we can update our <strong><em>DeviceService</em></strong> to inject notification service and it’s methods to notify when needed:</p><pre>@Service<br>class DeviceService(<br>  private val repository: DeviceRepository,<br>  private val listenerService: ListenerService = ListenerService(),<br>  private val notificationService: NotificationService<br>) {<br>  fun delete(id: String) {<br>    val device = findById(id)<br>    repository.deleteById(id).apply {<br>    notificationService.notify(<br>      Notification(<br>        title = &quot;Device deleted!&quot;,<br>        body = &quot;The device ${device.name} has been deleted!&quot;<br>      )<br>    )<br>  }<br>}</pre><p>Now, each time any device is deleted the devices with valid tokens will be notified as the following example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*feLrpi7GZBeO6VRbdVrJuw.png" /></figure><h4>Final thoughts</h4><p>Firebase is a powerful and scalable tool that allow us to build systems with personalized notifications across platforms trough Cloud Messaging. It&#39;s a beginner friendly and accessible (specially when relying on free tier) alternative for all kind of projects.</p><p>This article was a brief introduction for notifications and theres a lot of improvements that can be made (handling invalid tokens, cleaning our database, etc). You can checkout <a href="https://firebase.google.com/docs/cloud-messaging">the official documentation</a> for more.</p><h3>References and resources</h3><ol><li><a href="https://bitbucket.org/marelso/workspace/projects/SCHED">Project files</a></li><li><a href="https://www.youtube.com/watch?v=45w34u6nH_4">How to create a Firebase account</a></li><li><a href="https://firebase.google.com/docs/cloud-messaging">Firebase Cloud Messaging documentation</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fbd1cd761ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real time data with Server Sent Events]]></title>
            <link>https://medium.com/@marelso/real-time-data-with-server-sent-events-9d174b475567?source=rss-399a3ae568ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d174b475567</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[server-sent-events]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[sse]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Marelso]]></dc:creator>
            <pubDate>Wed, 27 Aug 2025 02:02:42 GMT</pubDate>
            <atom:updated>2025-08-27T02:54:00.702Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction to real-time connections</p><p>Server Sent Events (SSE) is a technology that allows the server to post updates to any connected client through a single and long-lived http connection.</p><h3>How Does SSE work?</h3><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events">SSE</a> uses a simple flow to establish the communication between server and clients:</p><ul><li>The client send a request to the server to listen a stream of events.</li><li>The server keeps this connection open until the client disconnects or the connection reaches timeout.</li><li>Then the server can send any update to the client that is listening through that connection.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*IBnvwpGlrBFPsxrgYLDUEg.png" /></figure><h3>Server Sent Events and Polling</h3><p>While SSE establish a connection with the server allowing it to push updates to the client, polling provides near real time information by having the clients performing new requests at fixed intervals.</p><p>Although polling is kinda easy to implement, making several requests it&#39;s a bad practice and inefficient approach since it will consume unnecessary resources (specially when there&#39;s no new data) and it will cause infrastructure costs to increase.</p><h3>Server Sent Events and Web Sockets</h3><p>There&#39;s a few differences between Server Sent Events (SSE) and Web Sockets (WS). In WS we work with a single and persistent TCP connection that supports two-way communication (meaning that both client and server can emit new messages at any time).</p><p>SSE allow us to work with HTTP connections making WS more complex to implement since it requires additional effort handling and managing connection state. Plus WS two-way connection (both client and server can sent updates) might be overkill especially when the client only needs to receive updates.</p><h3>Implementing Server Sent Events</h3><p>To better understand SSE we will work on a simple project responsible for managing a schedule system that will turn an LED light on and off in a ESP32 client when the current system time is between schedule&#39;s start and end time. The ESP32 device will handle schedules changes through SSE messages by fetching the device from API on each received message.</p><p>To achieve this we need a couple projects:</p><ul><li>The server built in Kotlin + Spring Boot</li><li>The client using c++ (but I&#39;ll add an sample with JS on backend repo)</li><li>Optional dashboard in jetpack compose (or project&#39;s <a href="http://localhost:8080/swagger-ui/index.html">swagger</a>)</li></ul><h3>Getting started</h3><p>I will focus on implementing SSE in an existing project with the standard CRUD operations. You can either follow the steps using the current setup or start a new project and implement the emitters necessary to it.</p><h3>Creating services</h3><p>I&#39;ll encapsulate all the listening and emitting logic inside <strong><em>ListenerService</em></strong> class that will manage the SSE clients. It will hold an <strong><em>MutableMap</em></strong> where the key is a String (that represents the entity id) and a mutable list of <strong><em>SseEmitter </em></strong>(each representing a client instance).</p><pre>class ListenerService {<br>    private val listeners = mutableMapOf&lt;String, MutableList&lt;SseEmitter&gt;&gt;()<br>}</pre><p>To subscribe clients to the listener we need a method that receives the entity id (representing the given entity that client will receive the updates). This method will also be responsible to instantiate the <strong><em>SseEmitter</em></strong> (that has information about the client) and adding it to our listeners list.</p><p>In order to instantiate the <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/SseEmitter.html"><strong><em>SseEmitter</em></strong></a> we can provide a timeout and set handlers for timeout and completion events. Here I&#39;m using zero (meaning no timeout).</p><pre>fun subscribe(entityId: String): SseEmitter = SseEmitter(0L).apply {<br>    onCompletion { removeEmitter(deviceId, this) }<br>    onTimeout { complete() }<br>    <br>    addEmitter(deviceId, this)<br>}</pre><p>We also need to provide a new endpoint to allow our clients to subscribe:</p><pre>@GetMapping(&quot;/{id}/subscribe&quot;, produces = [MediaType.TEXT_EVENT_STREAM_VALUE])<br>fun subscribe(@PathVariable id: String) = ResponseEntity.ok(service.subscribe(id))</pre><p>Our add method will check if the entity id is present at our listeners list, if doesn&#39;t, it will insert an entry for it with an empty list. After this check it will add the emitter at the entity id entry. This approach allow us to have many clients listen to an unique entry.</p><pre>private fun addEmitter(entityId: String, emitter: SseEmitter) {<br>  listeners.putIfAbsent(entityId, mutableListOf())<br>  listeners[entityId]?.add(emitter)<br>}</pre><p>We also need a method that will remove given client from the listeners (in complete or timeout events). This method will use the same approach as the addEmitter method. But, instead of adding, it will remove the client when the entityId is present at the list.</p><pre>private fun removeEmitter(entityId: String, emitter: SseEmitter) {<br>  listeners[entityId]?.apply {<br>    remove(emitter)<br>  }<br>}</pre><p>These steps cover all the client insertion and removal from our server. Now we need to notify our clients when some action is made at that given entity.</p><p>The way that we&#39;ll handle the notification to the clients depends on what your project needs. In my case it will notify for entity&#39;s schedule changes so I&#39;ve created an enum that has CREATED and DELETED entries.</p><pre>enum class EntityEvent {<br>  CREATED,<br>  DELETED;<br>}</pre><p>And these status will be sent in a message with the schedule&#39;s id that has been included or removed from the entity that our clients are listening.</p><pre>data class ListenerEvent(<br>  val scheduleId: String,<br>  val type: EntityEvent<br>)</pre><p>With this information, our client can handle the addition or removal of that given schedule at their side. We don&#39;t actually need to send any information. If our client only need to know that something have change we can notify by send Unit (equivalent to void in Java) instead of the <strong><em>ListenerEvent</em></strong></p><pre>fun notify(event: ListenerEvent) {<br>  listeners[event.deviceId]?.forEach { client -&gt;<br>    try { client.send(event) } // or try { client.send(Unit) }<br>    catch (e: Exception) { return@forEach }<br>  }<br>}</pre><h3>Notify clients</h3><p>Now that we have properly seted our listener class, we&#39;re able to notify the changes at our database through our API methods. In this project I will implement notifiers to <strong><em>Device&#39;s</em></strong> schedules PUT operations (inserting and removing schedules from given device).</p><p>To notify the clients we need to change our <strong><em>DeviceService</em></strong> class that perform&#39;s our database operations.</p><p>Let&#39;s start by updating<strong><em> addSchedule </em></strong>method to call the notify method after saving the changes on database.</p><pre>fun addSchedule(id: String, schedule: ScheduleCreateDTO): Device {<br>  if(schedule.end.isBefore(schedule.start)) <br>    throw RuntimeException(&quot;End of schedule can&#39;t be before start&quot;)<br>  }<br><br>  val device = findById(id)<br><br>  return repository.save(<br>    device.copy(schedules = device.schedules.plus(schedule.toSchedule())<br>  ).apply {<br>    listenerService.notify(ListenerMessage(id, ListenerAction.CREATED))<br>  }<br>}</pre><p>In the same way, we update <strong><em>removeSchedule</em></strong> method to notify the clients whenever a schedule is removed.</p><pre>fun removeSchedule(id: String, scheduleId: String): Device {<br>  val device = findById(id)<br><br>  return repository.save(<br>    device.copy(<br>      schedules = device<br>                .schedules<br>                .filterNot { it.id == scheduleId }<br>    ).apply {<br>      listenerService.notify(ListenerMessage(id, ListenerAction.DELETED))<br>    }<br>}</pre><h3>Implementing clients</h3><p>When working with web/js we can work with <strong><em>EventSource</em></strong> to listen to server&#39;s messages.</p><pre>const eventSource = new EventSource(<br>  `http://localhost:8080/api/v1/device/${id}/subscribe`<br>)<br><br>eventSource.onmessage = (event) =&gt; {<br>    console.log(event)<br>    fetchDevice()<br>}<br><br>eventSource.onerror = (error) =&gt; {<br>    console.error(&quot;Error occurred: &quot;, error)<br>    eventSource.close()<br>}</pre><p>Then, after receiving a message from the server, our <strong><em>ListenerMessage</em></strong> will be available at <strong><em>data</em></strong> field and we should have an output like this for including or removing schedules:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*aHNhjKOrwrwY9YasELAWcA.png" /><figcaption>Web JS and <strong><em>EventSource </em></strong>listener</figcaption></figure><p>When working with ESP32/C++ we can use <strong><em>HTTPClient</em></strong> to connect to server and listen to the changes on device&#39;s schedule</p><pre>void subscribe(Device &amp;device) {<br>  String url = &quot;http://localhost:8080/api/v1/device/&quot; + device.id + &quot;/subscribe&quot;;<br>  HTTPClient http;<br><br>  http.setTimeout(60000);<br>  http.setConnectTimeout(60000);<br><br>  http.addHeader(&quot;accept&quot;, &quot;text/event-stream&quot;);<br>  http.addHeader(&quot;connection&quot;, &quot;keep-alive&quot;);<br>  http.addHeader(&quot;User-Agent&quot;, &quot;ESP&quot;);<br><br>  http.begin(url);<br><br>  int httpCode = http.GET();<br><br>  if (httpCode &gt; 0) {<br>    Serial.println(&quot;Connected to SSE server&quot;);<br>    WiFiClient client = http.getStream();<br>    String eventData = &quot;&quot;;<br><br>    while (client.connected()) {<br>      while (client.available()) {<br>        char c = client.read();<br>        eventData += c;<br><br>        if (eventData.endsWith(&quot;\n\n&quot;)) {<br>          Serial.println(&quot;Received event: &quot;);<br>          Serial.println(eventData);<br>          eventData = &quot;&quot;;<br><br>          fetchDeviceById(device);<br>        }<br>      }<br>    }<br>  } else {<br>    Serial.println(&quot;Failed to connect to SSE server&quot; + httpCode);<br>  }<br>}</pre><p>Then this should be the output when receiving messages from schedule’s delete and create events:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*O-x_7wj0XYwMfmXGYc_bCQ.png" /><figcaption>ESP32 and C++ <strong><em>HTTPClient </em></strong>listener</figcaption></figure><h3>References and resources</h3><ol><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events">Server-Sent Events</a></li><li><a href="https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-ann-async.html#mvc-ann-async-sse">Server-Sent Events — Spring Boot</a></li><li><a href="https://bitbucket.org/marelso/schedule-backend/src/main/">Backend API repository</a></li><li><a href="https://bitbucket.org/marelso/schedule-esp/src/main/">ESP-32 client repository</a></li><li><a href="https://bitbucket.org/marelso/schedule-app/src/main/">Jetpack Compose dashboard repository</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d174b475567" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SDKMAN | Managing multiple SDKs]]></title>
            <link>https://medium.com/@marelso/sdkman-managing-multiple-sdks-6d9316a2ccdf?source=rss-399a3ae568ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d9316a2ccdf</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[sdk]]></category>
            <category><![CDATA[sdkman]]></category>
            <dc:creator><![CDATA[Marelso]]></dc:creator>
            <pubDate>Wed, 06 Mar 2024 15:26:10 GMT</pubDate>
            <atom:updated>2024-03-06T15:26:38.434Z</atom:updated>
            <content:encoded><![CDATA[<h4>Software Development Kit Manager</h4><p>When it comes to modern software development, it’s commonplace to juggle multiple projects using a variety of technologies, often with numerous versions of each one. This dynamic landscape can present significant challenges, requiring developers to constantly shift between different contexts, tools, and SDKs.</p><p>Setting up the development environment for each new project becomes a time-consuming necessity, consuming valuable time that could be better spent on actual coding. In light of these challenges, SDKMAN is a powerful solution to streamline this process, offering developers a more efficient and hassle-free approach to managing their development environments.</p><h3>What is SDKMAN</h3><p>SDKMAN is an versatile tool designed to manage multiple software development kits (SDKs). With SDKMAN, users can effortlessly switch between different versions of any SDK supported. This flexibility ensure optimal compatibility and efficiency within their development workflows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_RJPXKugVEPPcjVoUwlv2w.png" /><figcaption>SDKMAN logo</figcaption></figure><h3>Installation</h3><p>To install SDKMAN, you’ll need to utilize the terminal. Ensure you have curl support installed on your system. If not, you can install it by running:</p><pre>apt install curl</pre><p>After installing curl we can properly install sdkman by runing:</p><pre>curl -s &quot;https://get.sdkman.io&quot; | bash</pre><p>After the installation completes, run init script by running:</p><pre>source &quot;$HOME/.sdkman/bin/sdkman-init.sh&quot;</pre><p>If the installation is successful we can start using sdkman. First lets check the current version by runing:</p><pre>sdk version</pre><p>The output should be something like this:</p><blockquote><strong>SDKMAN!</strong> <br>script: 5.18.2 <br>native: 0.4.6</blockquote><h3>Managing SDKs</h3><p>With SDKMAN, users have access to a wide range of SDKs for efficient management. When working with the available SDKs, we can easily switching between installed versions. For example, to manage Java SDKs, simply use the following command:</p><pre>sdk list java</pre><p>This command will display the available Java versions, highlighting the currently installed versions and indicating the active one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*JtK2h4yxSbMhLf-qcOxAXQ.png" /><figcaption>list command output</figcaption></figure><p>In order to install a different version, you can just get the identifier from the list and execute the install command. If no identifier is provided, SDKMAN will install the latest stable version automatically.</p><pre>sdk install java 8.0.402-amzn</pre><p>If you don’t have any version installed, SDKMAN will set the one you’re installing as the default version. Additionally, when installing a new version, SDKMAN will prompt you to confirm if you want to make the newly installed version the default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*cwXHXzbn3z_4j4f_wzOAAA.png" /><figcaption>install command output</figcaption></figure><p>You can also switch between the installed versions easily using the use command.</p><pre>sdk use java 8.0.402-amzn</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*ZfrgieAdwdfe294Fhiiejg.png" /><figcaption>use command output</figcaption></figure><p>By running the java version command we can checkout the current version</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*0GCJ5XeibC-CXSoP-EGACQ.png" /><figcaption>java version output</figcaption></figure><p>SDKMAN also provide an easily way to check all the sdks versions in use</p><pre>sdk current</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*ayhu-Kv5u3PeS_fVZYxg3Q.png" /><figcaption>current command output</figcaption></figure><h3>Conclusion</h3><p>With SDKMAN, developers can focus more on coding and quality and less on setup tasks, accelerating the development process and delivering high-quality software solutions. Whether you’re a seasoned developer or just starting out, SDKMAN proves to be an indispensable tool in the modern developer’s toolkit.</p><p>By simplifying the installation and management of SDKs through intuitive commands, SDKMAN empowers developers to effortlessly switch between different versions, ensuring compatibility and flexibility across projects. Its ability to provide a wide range of versions and having a straightforward way to check the currently active SDK further enhances productivity and workflow efficiency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d9316a2ccdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack compose | Network requests with Retrofit]]></title>
            <link>https://medium.com/@marelso/jetpack-compose-network-requests-with-retrofit-99314caf249e?source=rss-399a3ae568ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/99314caf249e</guid>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Marelso]]></dc:creator>
            <pubDate>Sun, 29 Oct 2023 18:27:12 GMT</pubDate>
            <atom:updated>2024-03-02T08:08:03.841Z</atom:updated>
            <content:encoded><![CDATA[<p>Improve network operations in your Jetpack Compose app</p><p>When it comes to modern applications, It is frequently necessary to link them with some kind of external resource. Through this communication between applications, we can build more complex and robust functionalities without the need to implement all the flows that a particular feature needs. Instead, we can simplify this process by consuming an external method that performs this processing (as well as taking care of necessary validations), this approach allow us to decoupling this functionality from our application.</p><p>The use of these external resources brings several benefits. One of the most important is <strong>modularity</strong>: when something needs be changed or fixed, it will be done separately from our application. Not only do we not necessarily need to release a new update to our users, but we also reduce the possibility of introducing new bugs in our app.</p><p>This approach also brings benefits to the performance of our application. Since all processing is done externally, the application do not need to consume resources to perform this processing. And, as the external resource is specific to this particular functionality, it will probably do this more efficiently than we implementing this feature inside our app, as we have fewer resources available.</p><p><strong>What is Retrofit?<br></strong>Retrofit is a highly popular library for mobile development that can simply the process for making network request. Retrofit improve the efficiency of the network requests to make the communication between the client and the server more effective and, also, provides an simpler syntax to improve our code readability.</p><p><strong>What will we build?<br></strong>To better understand Retrofit and network requests, we will build an simple app that will display the content fetched from an remote data source, we will interact with it by making the most commonly used HTTP requests.</p><p>To achieve this I’ve set up a simple API with all the necessary methods, which you can check out <a href="https://github.com/marelso/post-backend"><strong>here</strong></a>. However, you can and should use any API of your choice if you want.</p><p><strong>Getting started<br></strong>If you’re working with Gradle, incorporate Retrofit dependency into your project’s <strong><em>build.gradle</em></strong> file. You can checkout <a href="https://mvnrepository.com/artifact/com.squareup.retrofit2/retrofit/2.9.0"><strong>here</strong></a><strong> </strong>for the most up-to-date version. As for my current setup, I’m using the following version:</p><pre>implementation &#39;com.squareup.retrofit2:retrofit:2.9.0&#39;</pre><p>Retrofit also provide an converter to translate the responses into Kotlin data. You can get it from <a href="https://mvnrepository.com/artifact/com.squareup.retrofit2/converter-gson/2.9.0"><strong>here</strong></a>, I’m using the following version:</p><pre>implementation &#39;com.squareup.retrofit2:converter-gson:2.9.0&#39;</pre><p>Before we start to build our app, I highly recommend you to create an Constant <strong>object</strong> to manage all the constants of the project (like urls, page size, tokens). You can achieve this by using the snippet above:</p><pre>object Constants {<br>    const val PAGE_SIZE: Int = 20<br>    object PostAPI {<br>        const val URL: String = &quot;http://localhost:8080/&quot;<br>        const val NAME = &quot;post_api&quot;<br>    }<br><br>    object SecondaryAPI {<br>        const val URL: String = &quot;http://localhost:8080/&quot;<br>        const val NAME = &quot;another_api&quot;<br>    }<br>}</pre><p>If you’re using an local server fill in “localhost” with your given IP.</p><h3>Creating services!</h3><p>Now that we have everything up and running, we need to create our first service. For this we will create an new Interface class. This interface serves as a contract or abstraction that defines the structure of our API requests. Here we will define our API’s methods with the necessary endpoints and responses.</p><p>As for my setup, this will be my Interface:</p><pre>interface PostService {<br>    @GET(&quot;/posts&quot;)<br>    suspend fun get(<br>        @Query(&quot;page&quot;) page: Int,<br>        @Query(&quot;size&quot;) size: Int = PAGE_SIZE<br>    ): Response&lt;Page&lt;Post&gt;&gt;<br><br>    @GET(&quot;/posts/{id}&quot;)<br>    suspend fun get(@Path(&quot;id&quot;) id: Int): Response&lt;Post&gt;<br><br>    @POST(&quot;/posts&quot;)<br>    suspend fun post(@Body post: Post): Response&lt;Post&gt;<br><br>    @PUT(&quot;/posts/{id}&quot;)<br>    suspend fun put(<br>        @Path(&quot;id&quot;) id: Int,<br>        @Body request: Post<br>    ): Response&lt;Post&gt;<br><br>    @PATCH(&quot;/posts/{id}&quot;)<br>    suspend fun patch(<br>        @Path(&quot;id&quot;) id: Int,<br>        @Query(&quot;status&quot;) status: Boolean<br>    ): Response&lt;Unit&gt;<br><br>    @DELETE(&quot;/posts/{id}&quot;)<br>    suspend fun delete(@Path(&quot;id&quot;) id: Int): Response&lt;Unit&gt;<br>}</pre><h3>Creating Retrofit instance!</h3><p>Now that we have an valid service, we need to create an instance of retrofit so that we can perform our http requests. There are a lot of ways to do this, one of the most common ways is to create an singleton <strong>object</strong> with both API&#39;s URL, Retrofit&#39;s instance builder and our service. You can follow the above example if you want to use this approach:</p><pre>object PostApi {<br>    private val retrofit: Retrofit by lazy {<br>        Retrofit.Builder()<br>            .baseUrl(PostAPI.URL)<br>            .addConverterFactory(GsonConverterFactory.create())<br>            .build()<br>    }<br><br>    val instance: PostService by lazy {<br>        retrofit.create(PostService::class.java)<br>    }<br>}</pre><p><strong>Using Retrofit with Koin!<br></strong>As I said in my previous post, embracing dependency injection (DI) in your projects brings several benefits. When we talk about network requests these advantages can be used. If you still don’t understand much about DI or even Koin, you can checkout <a href="https://medium.com/@marelso/jetpack-compose-dependency-injection-with-koin-12fbea31367a"><strong>here </strong></a>where I discuss about and explain how to use Koin.</p><p>To properly setup Retrofit using Koin I wrote this method that will provide an instance of Retrofit and using the Constant object I get the necessary service configuration. You can checkout the snippet above:</p><pre>private fun provideRetrofitInstance(<br>    url: String<br>): Retrofit {<br>    return Retrofit.Builder()<br>        .baseUrl(url)<br>        .addConverterFactory(GsonConverterFactory.create())<br>        .build()<br>}<br><br>val appModule = module {<br>    factory(named(PostAPI.NAME)) {<br>        provideRetrofitInstance(PostAPI.URL)<br>    }<br>    factory {<br>        get&lt;Retrofit&gt;(named(PostAPI.NAME))<br>            .create(PostService::class.java)<br>    }<br>    viewModel { ListViewModel(get()) }<br>}</pre><p><strong>How can we manage multiple APIs?<br></strong>When you need to handle multiple instances of Retrofit or any other service with Koin, you can do use of named method to distinguish these instances. By doing this, Koin will provide unique identifiers for each instance with the given String qualifier.</p><p>Here we use the <strong><em>provideRetrofitInstance</em></strong> method to get multiple instances of retrofit and then inject it inside the viewModel.</p><pre>val appModule = module {<br>    factory(named(PostAPI.NAME)) {<br>        provideRetrofitInstance(PostAPI.URL)<br>    }<br>    factory {<br>        get&lt;Retrofit&gt;(named(PostAPI.NAME))<br>            .create(PostService::class.java)<br>    }<br><br>    factory(named(SecondaryAPI.NAME)) {<br>        provideRetrofitInstance(SecondaryAPI.URL)<br>    }<br>    factory {<br>        get&lt;Retrofit&gt;(named(SecondaryAPI.NAME))<br>            .create(SecondaryService::class.java)<br>    }<br><br>    viewModel { ListViewModel(get(), get()) }<br>}</pre><p><strong>Dot not forget to setup your manifest file!<br></strong>Once you have everything properly configured, you should allow internet permission in your manifest and, depending on the Android version you are using, you may also need to enable clear text traffic.</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;<br><br>&lt;application<br>  ...<br>  android:usesCleartextTraffic=&quot;true&quot; &gt;<br>&lt;/application&gt;</pre><p>You shouldn’t use <strong><em>usesCleartextTraffic</em> </strong>in production environment as it is unencrypted and can pose a security risk. But, if your really need to allow this, you can follow this <a href="https://stackoverflow.com/questions/45940861/android-8-cleartext-http-traffic-not-permitted/50834600#50834600"><strong><em>stackoverflow</em></strong></a><strong><em> </em></strong>thread to properly allow only the necessary source.</p><p>After we have all up and running we can start making our requests. I am working with paging 3, so my ListViewModel currently are like this:</p><pre>class ListViewModel(<br>    private val service: PostService,<br>    private val secondaryService: SecondaryService<br>) : ViewModel() {<br>    val pagingData = Pager(PagingConfig(pageSize = 20)) {<br>        PostPagingSource(service)<br>    }.flow.cachedIn(viewModelScope)<br>}</pre><p>If you aren&#39;t using Koin, should include an property with the Retrofit instance, like this:</p><pre>private val service = PostApi.instance</pre><p>Here my paging source that is responsible to make the initial fetch request:</p><pre>class PostPagingSource(<br>    private val service: PostService<br>) : PagingSource&lt;Int, Post&gt;() {<br>    override suspend fun load(<br>      params: LoadParams&lt;Int&gt;<br>    ): LoadResult&lt;Int, Post&gt; {<br>      return try {<br>        val currentPage = params.key ?: 0<br>        val response = service.get(page = currentPage, size = PAGE_SIZE)<br>        val items: List&lt;Post&gt; = response.body()?.content ?: listOf()<br><br>        LoadResult.Page(<br>          data = items,<br>          prevKey = if (currentPage &lt;= 1) null else currentPage - 1,<br>          nextKey = if (items.isEmpty()) null else currentPage + 1<br>        )<br>      } catch (e: Exception) {<br>        LoadResult.Error(e)<br>      }<br>    }<br><br>    override fun getRefreshKey(state: PagingState&lt;Int, Post&gt;): Int? {<br>        TODO(&quot;Not yet implemented&quot;)<br>    }<br>}</pre><p>Using compose&#39;s lazy column we can render the necessary cards provided by the given remote data source.</p><pre>@Composable<br>fun PostList(posts: LazyPagingItems&lt;Post&gt;) {<br>    LazyColumn {<br>        items(posts.itemCount) { index -&gt;<br>            posts[index]?.let {<br>                PostCard(it)<br>            }<br>        }<br>    }<br>}</pre><p>The final result is an sequence of &quot;PostCard&quot; composable according to the API&#39;s response list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*oRGreYSOAyPjES05Sf36Hw.png" /></figure><p>Now that we successfully fetched data from our remote data source, lets try to request an specific resource using the Retrofit&#39;s <strong><em>GET</em></strong> method passing the reference. For this, I have created an new ViewModel that will handle the details of each card.</p><pre>class PostDetailViewModel(<br>    private val service: PostService, var reference: Int<br>) : ViewModel() {<br>    private val _postUiState = MutableStateFlow&lt;PostUiState&gt;(<br>        PostUiState.Loading<br>    )<br>    val postUiState: StateFlow&lt;PostUiState&gt; = _postUiState<br><br>    init {<br>        fetchContent()<br>    }<br><br>    private fun fetchContent() = viewModelScope.launch {<br>        val result = service.get(reference)<br><br>        _postUiState.value = if (result.isSuccessful) result.body()?.let {<br>            PostUiState.Success(it)<br>        } ?: PostUiState.Error(subtitle = &quot;Resource not found&quot;)<br>        else PostUiState.Error(<br>            subtitle = &quot;There was an error fetching: ${result.code()}&quot;<br>        )<br>    }<br><br>    fun refresh() = viewModelScope.launch {<br>        _postUiState.value = PostUiState.Loading<br>        fetchContent()<br>    }<br><br>    fun changePostStatus(status: Boolean) = viewModelScope.launch {<br>        service.patch(reference, status)<br>    }<br><br>    fun deletePost() = viewModelScope.launch {<br>        _postUiState.value = PostUiState.Loading<br>        val result = service.delete(reference)<br><br>        _postUiState.value = if(result.isSuccessful) PostUiState.Delete<br>        else PostUiState.Error(<br>            &quot;Some header message&quot;,<br>            &quot;Some error description&quot;<br>        )<br>    }<br>}</pre><p>I also created an sealed class to handle the states of my requests. When the ViewModel is created, we set the state as &quot;Loading&quot; and, while fetching the data, we can update this value to reflect inside our composable.</p><p>Here are my current states:</p><pre>sealed class PostUiState {<br>    object Loading : PostUiState()<br>    object Delete : PostUiState()<br>    data class Success(val post: Post) : PostUiState()<br>    data class Error(<br>        val headline: String = &quot;Something went wrong&quot;,<br>        val subtitle: String<br>    ) : PostUiState()<br>}</pre><p>By using <strong><em>fetchContent </em></strong>method we perform the <strong>GET </strong>request while composable observe our Ui States changes and, foreach change, we can respond in different ways.</p><pre>@Composable<br>fun PostDetailScreen(<br>    viewModel: PostDetailViewModel, navHostController: NavHostController<br>) {<br>    val postUiState = viewModel.postUiState.collectAsState()<br><br>    when (postUiState.value) {<br>        is PostUiState.Loading -&gt; PostDetailLoading()<br><br>        is PostUiState.Error -&gt; {<br>            val error = (postUiState.value as PostUiState.Error)<br>            PopError(<br>                headline = error.headline,<br>                subtitle = error.subtitle,<br>                onClick = {<br>                    refresh(viewModel)<br>                })<br>        }<br><br>        is PostUiState.Success -&gt; {<br>            val post = (postUiState.value as PostUiState.Success).post<br><br>            PostDetail(<br>                post = post,<br>                goBack = { goBack(navHostController, Screen.Home) },<br>                updateStatus = {<br>                    viewModel.changePostStatus(it)<br>                },<br>                delete = {<br>                    viewModel.deletePost()<br>                }<br>            )<br>        }<br><br>        is PostUiState.Delete -&gt; {<br>            DeleteCompleted(<br>                onClick = {<br>                    goBack(navHostController, Screen.Home)<br>                })<br>        }<br>    }<br>}</pre><p>The result is a dynamic screen that can respond to state changes, providing greater user interaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*TFec03K1KFrKAKn0j2b2EA.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*n4-WlywdmMSASpe8Oug7KA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*tU1oVC6i6L42S-EfZZxxHw.png" /><figcaption>Screens for each request state</figcaption></figure><p>Now that we have the detail screen properly populated, we can realize the patch request. In my case this request will update the &quot;status&quot; field. We will update this value according to the user interaction with the switch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*59rVdiPlgkPVYgvzgTGOkw.png" /><figcaption>Preview of the detail</figcaption></figure><pre>var status by remember { mutableStateOf(post.status) }<br>Switch(checked = status, onCheckedChange = {<br>    status = it<br>    updateStatus.invoke(status)<br>})</pre><p>The checked change will trigger the viewModel&#39;s <strong><em>changePostStatus</em></strong> method passing the new status value then the viewModel will make the patch request to our remote data source.</p><pre>fun changePostStatus(status: Boolean) = viewModelScope.launch {<br>        service.patch(reference, status)<br>}</pre><p>To implement the delete method we can use an similar approach of GET request, When the user hits the delete button the ViewModel will emit the Loading state and make the delete request passing the reference field.</p><p>If the new request is successful and the resource has been deleted by the service, we can show an screen with a message to user navigate back to the home screen. If anything goes wrong we can pop the error screen so the user can retry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*-6foSh52gqSL8MZrf7QDMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*htoItDKdVFXT09gEr7BWlg.png" /></figure><p>With requests to retrieve all available resources and updating it in our remote data source all that’s left is to create a new resource in our API.</p><p>I have an form that have all the necessary fields with some steps</p><pre>@Composable<br>fun CreatePostScreen(viewModel: CreatePostViewModel = getViewModel(), navHostController: NavHostController) {<br>    CreatePostForm(<br>        viewModel = viewModel,<br>        goBack = { goBack(<br>            navHostController = navHostController,<br>            screen = Screen.Home<br>        )}<br>    )<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5fhymZrZyB4qXSaSCnxyw.png" /><figcaption>Steps for posting</figcaption></figure><p>I also created another viewModel to handle the post request and Post data object fields</p><pre>class CreatePostViewModel(private val service: PostService) : ViewModel() {<br>    var headline = mutableStateOf(&quot;&quot;)<br>    var description = mutableStateOf(&quot;&quot;)<br>    var content = mutableStateOf(&quot;&quot;)<br>    var previewImage = mutableStateOf(&quot;&quot;)<br>    var bannerImage = mutableStateOf(&quot;&quot;)<br>    var status = mutableStateOf(true)<br>    private val _postUiState = MutableStateFlow&lt;CreateUiState&gt;(<br>        CreateUiState.Loading<br>    )<br>    val state: StateFlow&lt;CreateUiState&gt; = _postUiState<br><br>    fun create() = viewModelScope.launch {<br>        _postUiState.value = CreateUiState.Loading<br><br>        val post = Post(<br>            headline = headline.value,<br>            description = description.value,<br>            content = content.value,<br>            previewImage = previewImage.value,<br>            bannerImage = bannerImage.value,<br>            status = status.value<br>        )<br><br>        val result = service.post(post)<br><br>        _postUiState.value = if (result.isSuccessful) CreateUiState.Success<br>        else CreateUiState.Error<br>    }<br>}</pre><h3>Conclusion</h3><p>When it comes to network requests, doing use of Retrofit can open up a world of possibilities. By leveraging modularity and doing use of external resources you can optimize performance and reduce complexity inside your app. Retrofit proves to do a great job when speaking about simplifying network requests not only improving efficiency but also enhancing the code readability with its clean syntax.</p><p>Along this journey, we explored creating services, Retrofit instances, and managing various UI states according to service responses. With these insights, you will be able to improve connectivity, speed up your app through interactivity and, most importantly, reduce bugs within your applications. I hope this guide was helpful in your learning about network requests.</p><h3>References</h3><ol><li><a href="https://github.com/marelso/post-thread-app">Project repository</a></li><li><a href="https://github.com/marelso/post-backend">Backend API Repository</a></li><li><a href="https://square.github.io/retrofit/">Retrofit documentation</a></li><li><a href="https://developer.android.com/jetpack">Jetpack compose</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99314caf249e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose | Dependency injection with Koin!]]></title>
            <link>https://medium.com/@marelso/jetpack-compose-dependency-injection-with-koin-12fbea31367a?source=rss-399a3ae568ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/12fbea31367a</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[composables]]></category>
            <category><![CDATA[koin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Marelso]]></dc:creator>
            <pubDate>Sat, 21 Oct 2023 14:36:57 GMT</pubDate>
            <atom:updated>2023-10-21T14:36:57.588Z</atom:updated>
            <content:encoded><![CDATA[<p>Unlock the power of Koin in your projects</p><p><strong>What is dependency injection?<br></strong>Dependency Injection is a software design pattern used in object-oriented programming and software engineering. It is one of the techniques that aim to facilitate the segregation of responsibilities in object-oriented programming. Instead of creating dependencies within the context, objects are able to pass these dependencies to another object that needs it. This helps in disconnecting the code, so it becomes more flexible and manageable. In DI, dependencies are typically through constructor injection, setter/injection, and method injection.</p><p>In short, is a crucial notion in software development aimed to achieve the objectives of robustness, testing, and easy adaptability. It is advisable to embrace DI as it enables the development of stronger and scalable software which is also easy to maintain or expand in the future. In Kotlin, Koin is a great DI framework that makes it easy to implement your DI approach in the Kotlin apps you utilize. It minimizes boilerplate code, enhancing the overall developer experience and making the codebase more approachable.</p><p><strong>Understanding Koin<br>What is Koin?<br></strong>With Koin, you can easily configure and inject dependencies throughout your application, making it more modular and easier to maintain with minimal boilerplate code. It is often referred to as a “<a href="https://insert-koin.io/">pragmatic DI framework</a>” because it’s lightweight, easy to use and provides a DSL (domain-specific language) for defining and resolving dependencies.</p><p><strong>What will we build?<br></strong>To understand Koin and DI principles we will build an simple composable that will display the content fetched from a ViewModel, and will also update values from it.</p><p>To achieve this I have this simple viewModel that only returns hardcoded code, but if you want you can inject any other dependencies to make the content more dynamic.</p><pre>class AppViewModel : ViewModel() {<br>    private val _name = mutableStateOf(&quot;Marelso&quot;)<br>    val name: State&lt;String&gt; = _name<br><br>    fun getImage() = &quot;Any image url&quot;<br><br>    fun updateName(name: String) { _name.value = name }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*sZ-X2GruLG1ntRWAM52Mnw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*45jeSEbHpe3al8pUtTDXMg.png" /><figcaption>App preview</figcaption></figure><p><strong>Getting started<br></strong>If you’re working with Gradle, incorporate Koin dependency into your project’s <em>build.gradle</em> file. You can checkout <a href="https://mvnrepository.com/artifact/io.insert-koin/koin-androidx-compose">here</a> for the most up-to-date version. As for my current setup, I’m using the following version:</p><pre>implementation &#39;io.insert-koin:koin-androidx-compose:3.2.0&#39;</pre><h3>Your first Koin module!</h3><p><strong>Create an dependency injection package<br></strong>When using Koin, we can use modules for holding out dependencies, this allow us to create a more flexible environment. In order to do this, we have to build a new Kotlin file to declare all the modules we need. Koin provide us the “<em>module</em>” method that can be used to declare the new module.</p><pre>val appModule = module {<br>    viewModel { AppViewModel() }<br>}</pre><p>Having incorporated the Koin library and defined your initial module, its time to create an Application to manage these modules. You can use the following snippet as a guide:</p><pre>class App: Application() {<br>    override fun onCreate() {<br>        super.onCreate()<br><br>        startKoin {<br>            androidContext(this@App)<br>            modules(appModule)<br>        }<br>    }<br>}</pre><p>When you’ve finished configuring your project to start using Koin, be sure that your AndroidManifest.xml file is correctly configured and pointing to your custom application class. If it’s not the case update the &lt;application&gt; tag accordingly:</p><pre>&lt;application<br>  android:name=&quot;.App&quot; &gt;<br>&lt;/application&gt;</pre><h3>Using dependencies in compose</h3><p>With our dependencies ready to go, it’s time to do some use to them in our Composables. We can inject the provided ViewModel by using “<strong><em>getViewModel</em></strong>” method from Koin.</p><pre>@Composable<br>fun Greeting(modifier: Modifier = Modifier,<br> viewModel: AppViewModel = getViewModel()<br>) {<br>    val observableName by remember { viewModel.name }<br><br>    val painter: ImagePainter = rememberImagePainter(<br>        data = viewModel.getImage(),<br>        builder = {<br>            crossfade(true)<br>        }<br>    )<br><br>    var text by remember { mutableStateOf(&quot;&quot;) }<br>    <br>    Column (<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .padding(16.dp),<br>        verticalArrangement = Arrangement.Center,<br>        horizontalAlignment = Alignment.CenterHorizontally<br>    ) {<br><br>        TextField(<br>            value = text,<br>            onValueChange = {<br>                viewModel.updateName(it)<br>                text = viewModel.name.value<br>            },<br>            label = { Text(&quot;Enter your name&quot;) },<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .padding(32.dp)<br>        )<br><br>        Spacer(modifier = Modifier.height(32.dp))<br><br>        Image(<br>            painter = painter,<br>            contentDescription = &quot;Image Description&quot;,<br>            modifier = Modifier<br>                .width(80.dp)<br>                .height(80.dp)<br>                .clip(CircleShape),<br>            contentScale = ContentScale.Crop<br>        )<br><br>        Spacer(modifier = Modifier.height(16.dp))<br><br>        Text(<br>            text = observableName,<br>            modifier = modifier<br>        )<br>    }<br>}</pre><h3>Conclusion</h3><p>When discussing Jetpack compose, the use of dependency injection through Koin brings several benefits by improving the modularity and maintainability of projects developed using the framework. Dependency injection is an fundamental concept in modern software development, promoting flexibility, testability, and separation of concerns. Koin simplifies the configuration and injection of dependencies, minimizing boilerplate code and making your application more modular.</p><p>The UI effortlessly interacts with the ViewModel, displaying dynamic content fetched through dependency injection. This approach not only enhances the development experience but also aligns with principles that foster scalable, robust, and maintainable software.</p><p><strong>References</strong></p><ol><li><a href="https://github.com/marelso/di_with_koin"><em>Project repository</em></a></li><li><a href="https://developer.android.com/jetpack/compose"><em>Jetpack compose</em></a></li><li><a href="https://insert-koin.io/docs/reference/koin-compose/compose"><em>Koin</em></a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12fbea31367a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>