<?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 GokcenYener on Medium]]></title>
        <description><![CDATA[Stories by GokcenYener on Medium]]></description>
        <link>https://medium.com/@gokcensolmaz?source=rss-9480b0fee67b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*URUp4Ctz61fduGy5.jpg</url>
            <title>Stories by GokcenYener on Medium</title>
            <link>https://medium.com/@gokcensolmaz?source=rss-9480b0fee67b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:00:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gokcensolmaz/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[Data Transfer Between Screens on Android]]></title>
            <link>https://medium.com/@gokcensolmaz/data-transfer-between-screens-on-android-e0f0d90881a0?source=rss-9480b0fee67b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0f0d90881a0</guid>
            <category><![CDATA[json-serialization]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[parcelable-android]]></category>
            <category><![CDATA[data-transfer]]></category>
            <dc:creator><![CDATA[GokcenYener]]></dc:creator>
            <pubDate>Tue, 25 Feb 2025 15:26:54 GMT</pubDate>
            <atom:updated>2025-02-25T15:26:54.643Z</atom:updated>
            <content:encoded><![CDATA[<h4>Comparing Parcelable vs JSON Serialization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_g_NHkoWnMcXhZD89VrdA.png" /></figure><p>I am currently developing an e-commerce-like project where I need to navigate from a product list screen to a product detail screen. While implementing this, I saw that ChatGPT recommended a different approach than the one I previously used. I asked to Gemini, ensure to best practice, Gemini suggested using the method I’d already known. Curious about the differences between these two methods and researched them. I would like to share with you the comparison of the two methods recommended by ChatGPT and Gemini for Data Transfer Between Screens.</p><p><strong>Gemini’s Approach: Using Parcelable and @Parcelize</strong></p><p>Parcelable is an Android-specific interface, designed for efficient and fast data transfer between components (Activity, Fragment, Jetpack Navigation) within the application.</p><p>It allows objects to be converted into binary format and transferred, just like Java’s Serializable. Thanks to being optimized for Android, it is a faster solution compared to Java’s Serializable and JSON conversion. It provides convenience for developers by containing less boilerplate code compared to other serialization methods.</p><p>However, this Android-specific nature can also be considered a disadvantage since it cannot be used in multiplatform projects.</p><p><strong>Chatgpt’s Approach: JSON Serialization</strong></p><p>Converting objects to JSON format with libraries such as Gson or Kotlinx-Serialization and transferring them between screens is a solution that supports multiplatform (KMP, web, server, Android) support, unlike Parcelable. Moreover, JSON serialization allows storing data in databases, interacting with APIs, and performing WebSocket transactions.</p><p>Since it does not convert the data into binary format, it can be easily logged and manipulated during debug operations.</p><p>On the other hand, JSON serialization generally performs slower than Parcelable because of the additional serialization (object → JSON) and deserialization (JSON → object) steps.</p><p><em>As a result,</em></p><p>- If only fast and optimized data transfer between components within the Android application is required, using Parcelable is more advantageous.</p><p>- If multiplatform support or use with API/database is in question, using JSON serialization may be a better decision.</p><p>- Also, it is easier to read and manage JSON data with JSON Serialization in debug and logging processes.</p><p>Since I plan to support my project on a multiplatform basis in the future, I decided to proceed with JSON Serialization. However, for learning and sharing purposes, I’ve implemented and experimented with both approaches. You can review the codes of the two approaches below.</p><p><strong>Parcelable:</strong></p><ol><li>Add plugin to `build.gradle.kts`</li></ol><pre>plugins {<br>    id(&quot;kotlin-parcelize&quot;)<br>}</pre><p>2. Make `ProductUiModel` Parcelable</p><pre>@Parcelize<br>data class ProductUiModel(<br>    val id: String,<br>    val title: String,<br>    val brand: String,<br>    val imageUrl: String,<br>    val categories: List&lt;String&gt;,<br>    val productDepotInfoList: List&lt;ProductDepotInfoUiModel&gt;<br>) : Parcelable</pre><blockquote>Any nested complex object within a Parcelable model must also implement Parcelable.</blockquote><p>Since my `productDepotInfoList` field is a complex object I made `ProductDepotInfoUiModel` Parcelable too.</p><pre>@Parcelize<br>data class ProductDepotInfoUiModel(<br>    val depotId: String,<br>    val depotName: String,<br>    val price: Double,<br>    val marketAdi: String,<br>    val latitude: Double,<br>    val longitude: Double,<br>    val indexTime: String<br>) : Parcelable</pre><p>3. Pass `ProductUiModel`using `SavedStateHandle`</p><pre>@Composable<br>fun ProductCard(product: ProductUiModel, navController: NavHostController) {<br>    Card(<br>        modifier = Modifier<br>            .padding(4.dp)<br>            .clickable {<br>                navController.currentBackStackEntry<br>                    ?.savedStateHandle<br>                    ?.set(&quot;product&quot;, product)<br><br>                navController.navigate(Destination.ProductDetailScreen.route)<br>            }<br><br>    ) {<br>        Text(text = product.title ?: &quot;No Title&quot;)<br>      }<br>}</pre><p>4. Retrieve Object in `ProductDetailScreen`</p><pre>@Composable<br>fun AppNavGraph(modifier: Modifier = Modifier, navController: NavHostController) {<br>    NavHost(<br>        navController = navController,<br>        startDestination = Destination.HomeScreen.route<br>    ) {<br>        composable(Destination.HomeScreen.route) {<br>            HomeScreen(modifier = modifier, navController = navController)<br>        }<br>        composable(Destination.ProductDetailScreen.route) {<br>            val product = navController.previousBackStackEntry<br>                ?.savedStateHandle<br>                ?.get&lt;ProductUiModel&gt;(&quot;product&quot;)<br><br>            product?.let {<br>                ProductDetailScreen(product = it)<br>            }<br>        }<br><br>    }<br>}</pre><h4>JSON Serialization :</h4><ol><li>Add Gson dependency to `build.gradle.kts`.</li></ol><pre>implementation(&quot;com.google.code.gson:gson:2.10.1&quot;)<br><br>/***For toml.library: ***/<br>implementation(libs.gson)<br>//in toml.library:<br>[versions]<br>gson = &quot;2.10.1&quot;<br>[libraries]<br>gson = { module = &quot;com.google.code.gson:gson&quot;, version.ref = &quot;gson&quot; }</pre><p>2. Define JSON Serialization/Deserialization helper functions</p><pre>fun productToJson(product: ProductUiModel): String {<br>    return Gson().toJson(product)<br>}<br><br>fun jsonToProduct(json: String): ProductUiModel {<br>    return Gson().fromJson(json, ProductUiModel::class.java)<br>}</pre><p>3. Pass the object as JSON to in navigation.</p><pre>@Composable<br>fun ProductCard(product: ProductUiModel, navController: NavHostController) {<br>   <br>    Card(<br>        modifier = Modifier<br>            .padding(4.dp)<br>            .clickable {<br>                val productJson = productToJson(product)<br>                navController.currentBackStackEntry<br>                    ?.savedStateHandle<br>                    ?.set(&quot;product&quot;, productJson)<br><br>                navController.navigate(Destination.ProductDetailScreen.route)}<br><br>    ) {<br>        Text(text = product.title ?: &quot;No Title&quot;)<br>      }<br>}</pre><p>4. Setup the Navigation route to receive JSON</p><pre>@Composable<br>fun AppNavGraph(modifier: Modifier = Modifier, navController: NavHostController) {<br>    NavHost(<br>        navController = navController,<br>        startDestination = Destination.HomeScreen.route<br>    ) {<br>        composable(Destination.HomeScreen.route) {<br>            HomeScreen(modifier = modifier, navController = navController)<br>        }<br>        composable(Destination.ProductDetailScreen.route) {<br>            val productJson = navController.previousBackStackEntry<br>                ?.savedStateHandle<br>                ?.get&lt;String&gt;(&quot;product&quot;)<br><br>            productJson?.let {<br>                val product = jsonToProduct(it) <br>                ProductDetailScreen(product = product)<br>            }<br>        }<br><br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0f0d90881a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Lifecycle Callbacks]]></title>
            <link>https://medium.com/@gokcensolmaz/android-lifecycle-callbacks-66cedd7ebf6d?source=rss-9480b0fee67b------2</link>
            <guid isPermaLink="false">https://medium.com/p/66cedd7ebf6d</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[lifecycle-with-example]]></category>
            <category><![CDATA[lifecycle-callbacks]]></category>
            <category><![CDATA[activity-lifecycle]]></category>
            <category><![CDATA[lifecycle-methods]]></category>
            <dc:creator><![CDATA[GokcenYener]]></dc:creator>
            <pubDate>Mon, 03 Jun 2024 12:13:26 GMT</pubDate>
            <atom:updated>2024-06-03T12:13:26.232Z</atom:updated>
            <content:encoded><![CDATA[<p>As an Android developer, one of the most common questions I encounter in interviews is about the Activity Lifecycle. I wanted to discuss it using a messaging app example. Hoping it makes the explanation more understandable and memorable.</p><p>Before we delve into the Activity Lifecycle, let’s answer the question: What is an Activity?</p><p><strong>What is an Activity?</strong></p><p>In Android, an Activity represents the functionality that the application provides on a single screen. Each activity has a window that can interact with the user and is one of the fundamental building blocks of Android applications. Activities manage the different tasks, screens, or user interfaces of applications. When a user navigates from one screen to another within an application, they might actually be transitioning from one activity to another.</p><blockquote>Here, I would like to open a parenthesis on the subject of <strong>Activities with Jetpack Compose.</strong></blockquote><blockquote>With Jetpack Compose, unlike traditional XML layouts, usually, a single Activity is used, and all UI in this Activity is defined using composable functions. This structure eliminates the need to create multiple activities to manage different screens of the application and manages all screen switching operations through components like NavHost and NavController. These components dynamically change which content is displayed in the user interface. This simplifies the application architecture and can improve performance.</blockquote><p><strong>What are the Activity Lifecycle methods?</strong><br>In Android, every Activity has a specific lifecycle that defines transitions between various states of an Activity and the actions that can be performed in these states. The Android operating system provides various <em>callback</em> methods to manage the states of Activities. These methods are called automatically, starting from the creation of the Activity, until it is viewed by the user, paused and finally destroyed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/0*kvjlx87ePS3_VWzS.png" /><figcaption><a href="https://developer.android.com/guide/components/activities/activity-lifecycle">Activity Lifecycle</a></figcaption></figure><p>An example messaging application might use these methods in a variety of ways to improve user experience, ensure data security, and optimize resource management. Here are the potential uses of these methods in a messaging application:</p><p><strong>onCreate():</strong> When the application is launched, the onCreate() method loads the list of chats to be displayed on the main screen. Here, user interface elements are initialized, and the latest states of chats are retrieved from the disk or a local database. Additionally, all necessary permissions are checked and requested at this stage.</p><p><strong>onStart():</strong> When the user opens the app and it becomes visible, the onStart() method checks for new messages or updates from the server. This ensures that the application always presents the most up-to-date information to the user.</p><p><strong>onResume():</strong> If the user switches to another app and then returns to the messaging app, the onResume() method checks for new notifications received in the background and updates the interface. Also, when the app becomes active again, it may re-build WebSocket connections for instant messaging.</p><p><strong>onPause():</strong> When the user leaves the app, the onPause() method can activate security measures such as screenshot protection for sensitive information. Additionally, real-time processes like live audio or video calls can be paused or the user can be notified.</p><p><strong>onStop():</strong> When the app is completely hidden from the user, the onStop() method can temporarily stop some background services to reduce power consumption. For example, features that require continuous data updates, like location sharing, can be deactivated.</p><p><strong>onRestart():</strong> When the app is restarted, the onRestart() method reverses any stop or pause operations, restoring the app to its previous active state. This may include resuming interrupted chats or calls.</p><p><strong>onDestroy():</strong> When the app is completely closed or terminated due to an error, the onDestroy() method releases all resources and closes any open database connections. Additionally, all session information is securely cleared to ensure a clean start on the next launch of the app.</p><p>Using each lifecycle method in this way helps optimize both the performance and the user experience of the application. Especially for a messaging app, real-time data updates and resource management are critically important.</p><p>I hope you liked my article. If you have any questions or feedback, please feel free to contact me.</p><p><a href="https://www.linkedin.com/in/g%C3%B6k%C3%A7en-solmaz/">https://www.linkedin.com/in/gökçen-solmaz/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66cedd7ebf6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clarifying The Concept of Dependency Injection]]></title>
            <link>https://medium.com/@gokcensolmaz/clarifying-the-concept-of-dependency-injection-3d6de0b57057?source=rss-9480b0fee67b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d6de0b57057</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[inversion-of-control]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[dagger-hilt]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[GokcenYener]]></dc:creator>
            <pubDate>Tue, 02 Apr 2024 21:00:33 GMT</pubDate>
            <atom:updated>2024-04-02T21:00:33.175Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding the Power of Dependency Injection, Manual and Automated: From Concepts to Practical Implementation in Android Development</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*O5NOOLe9ACb-NGQg4RaXEQ.png" /></figure><h4>What is Dependency?</h4><p>To illustrate the concept of dependency in Dependency Injection, consider two classes, A and B. When class A utilizes functionality from class B, we say that class A has a dependency on class B. This refers that an object of class B is created within class A, making class A depends on class B. As a result, any modifications to class B will required accessing and modifying class A.</p><p>In this scenario, class B becomes the dependency, while class A becomes dependant.</p><pre>class DependencyB {<br>    fun doSomething() {<br>        println(&quot;Doing something in dependency&quot;)<br>    }<br>}<br><br><br><br>class DependentA {<br><br>    private val dependency: DependencyB = DependencyB()<br><br>    fun useDependency() {<br>        dependency.doSomething()<br>    }<br>}<br><br><br>fun main() {<br>    val dependentA = DependentA()<br><br>    dependentA.useDependency()<br>}</pre><h4>Why Dependency Injection?</h4><p>When a class relies on the functionality of only one other class, modifying that single dependency might not seem problematic.</p><p>What if there are more than one class that creates class B within? Because these classes are independent from each other, any changes on class B require modifying each classes separately. These processes invite new errors, require more code, and naturally consume more time.</p><p>Additionally, since the code is not reusable, it causes code repeats. As a result, it becomes too hard to handle and test.</p><h4>Dependency Injection comes into play</h4><p>Dependency injection is a programming technique that makes a class independent of its dependencies. It achieves that by decoupling the usage of an object from its creation. Dependencies are given externally instead of managing them within the class. In this way, the creation and management of the dependent object is done outside the class and some of the dependency is reduced.</p><p>We can create, provide, and manage the dependencies of the different classes ourselves, without needing a library. This is called <em>dependency injection by hand</em>, or <em>manual dependency injection</em>. But more dependencies and classes can make manual injection of dependencies more tedious. There are libraries that solve this problem by automating the process of creating and providing dependencies. This is called <em>automated dependency injection.</em></p><p>There are 3 types of Manual Dependency Injection:</p><ul><li>Constructor Injection</li><li>Setter Injection</li><li>Interface Injection</li></ul><p>(I am just talking about constructor injection for manual dependency injection.)</p><p>For an easy comparison, first, look at the code without DI:</p><pre>// Without DI<br>class DependencyA {<br>    fun doSomething() {<br>        println(&quot;Doing something in dependency&quot;)<br>    }<br>}<br><br>class DependentD() {<br>    private val dependency: DependencyA = DependencyA()<br>    fun useDependency() {<br>        dependency.doSomething()<br>    }<br>}<br>class DependentE() {<br>    private val dependency: DependencyA = DependencyA()<br>    fun useDependency() {<br>        dependency.doSomething()<br>    }<br>}<br>class DependentF() {<br>    private val dependency: DependencyA = DependencyA()<br>    fun useDependency() {<br>        dependency.doSomething()<br>    }<br>}<br><br>fun main() {<br>    val dependentD = DependentD()<br>    val dependentE = DependentE()<br>    val dependentF = DependentF()<br><br>    dependentD.useDependency()<br>    dependentE.useDependency()<br>    dependentF.useDependency()<br>}</pre><h4>Constructor Injection</h4><pre>// Constructor Injection<br>class DependencyA {<br>    fun doSomething() {<br>        println(&quot;Doing something in dependency&quot;)<br>    }<br>}<br><br>class DependentD(private val dependency: DependencyA) {<br>    fun useDependency() {<br>        dependency.doSomething()<br>    }<br>}<br>class DependentE(private val dependency: DependencyA) {<br>    fun useDependency() {<br>        dependency.doSomething()<br>    }<br>}<br>class DependentF(private val dependency: DependencyA) {<br>    fun useDependency() {<br>        dependency.doSomething()<br>    }<br>}<br><br>fun main() {<br>    val dependency = DependencyA()<br><br>    val dependentD = DependentD(dependency)<br>    val dependentE = DependentE(dependency)<br>    val dependentF = DependentF(dependency)<br><br>    dependentD.useDependency()<br>    dependentE.useDependency()<br>    dependentF.useDependency()<br>}</pre><p>It seems like nothing much has changed, we just moved one line from Dependent to the constructor. Moreover, we had to create an extra object for dependency in the main function.</p><p>So what good does dependency injection do for us? With the simplest example, let’s make a small change in the DependencyA class so that the DependencyA class now has a constructor and takes a parameter called name. So what would change in our code without Dependency Injection?</p><pre>// Without DI<br>class DependencyA(val name: String) {<br>    fun doSomething() {<br>        println(&quot; $name is doing something &quot;)<br>    }<br>}<br><br><br>class DependentD {<br>    private val dependency: DependencyA = DependencyA(name = &quot;D&quot;)<br><br>    fun useDependency() {<br>        dependency.doSomething()<br>    }<br>}<br>class DependentE {<br>    private val dependency: DependencyA = DependencyA(name = &quot;E&quot;)<br><br>    fun useDependency() {<br>        dependency.doSomething()<br>    }<br>}<br>class DependentF {<br>    private val dependency: DependencyA = DependencyA(name = &quot;F&quot;)<br><br>    fun useDependency() {<br>        dependency.doSomething()<br>    }<br>}<br><br><br>fun main() {<br>    val dependentD = DependentD()<br>    val dependentE = DependentE()<br>    val dependentF = DependentF()<br><br>    dependentD.useDependency()<br>    dependentE.useDependency()<br>    dependentF.useDependency()<br>}</pre><p>We added the parameter to the DependencyB class in each dependent class separately. Don’t be fooled by the fact that the codes are on a single page here. DependentD, DependentE and DependentF may be in different packages, and finding them and not missing them in large projects can be quite challenging. Having an overlooked class may also cause your application to stop working. Now let’s make the same change with Dependency Injection.</p><pre><br>// Constructor Injection<br>class DependencyA(val name: String) {<br>    fun doSomething() {<br>        println(&quot;$name is doing something in dependency &quot;)<br>    }<br>}<br><br>class DependentD(private val dependency: DependencyA) {<br>    fun useDependency() {<br>        dependency.doSomething()<br>    }<br>}<br><br>class DependentE(private val dependency: DependencyA) {<br>    fun useDependency() {<br>        dependency.doSomething()<br>    }<br>}<br><br>class DependentF(private val dependency: DependencyA) {<br>    fun useDependency() {<br>        dependency.doSomething()<br>    }<br>}<br><br><br>fun main() {<br><br>    val dependency = DependencyA(&quot;SomeOne&quot;)<br><br>    val dependentD = DependentD(dependency) //DependentD(DependencyA(&quot;D&quot;))<br>    val dependentE = DependentE(dependency) //DependentE(DependencyA(&quot;E&quot;))<br>    val dependentF = DependentF(dependency) //DependentF(DependencyA(&quot;F&quot;))<br><br>    dependentD.useDependency()<br>    dependentE.useDependency()<br>    dependentF.useDependency()<br>}</pre><p>As you can see, we were able to add to the code only in the class where the change was made, without touching any dependent classes. Dependency Injection basically provides us with such easy usage.</p><p>Before moving on to Automated Dependency Injection, I would like to give an example so that we can understand this part better. Next, we will talk about Automated Dependency Injection and Dagger Hilt.</p><p>In our example, let’s say we have battery-powered devices. Radio, Clock and Lamp need batteries to work, so they are battery dependent. Let’s write an implementation of this project without using dependency injection:</p><pre>//DependencyA<br>class Battery() {<br>    fun printBatteryLevel() {<br>        println(&quot;Battery level is 80%&quot;)<br>    }<br>}<br><br>//DependentD<br>class Clock() { <br>    private val battery: Battery = Battery()<br><br>    fun useBattery() {<br>        battery.printBatteryLevel()<br>    }<br>}<br><br>//DependentE<br>class Radio{<br>    private val battery: Battery = Battery()<br><br>    fun useBattery() {<br>        battery.printBatteryLevel()<br>    }<br>}<br><br>//DependentF<br>class Lamp {<br>    private val battery: Battery = Battery()<br><br>    fun useBattery() {<br>        battery.printBatteryLevel()<br>    }<br>}<br><br>fun main() {<br><br>    val clock = Clock()<br>    val radio = Radio()<br>    val lamp = Lamp()<br><br>    clock.useBattery()<br>    radio.useBattery()<br>    lamp.useBattery()<br>}</pre><p>Depending on the requirements of the project, when we add a new parameter to the Battery class, we will need to make changes to all classes that use the Battery class in the project.</p><pre>//DependencyA<br>class Battery(val batteryLevel: Int) {<br>    fun printBatteryLevel() {<br>        println(&quot;Battery level is $batteryLevel%&quot;)<br>    }<br>}<br><br>//DependentD<br>class Clock() { <br>    private val battery: Battery = Battery(batteryLevel = 80)<br><br>    fun useBattery() {<br>        battery.printBatteryLevel()<br>    }<br>}<br><br>//DependentE<br>class Radio{<br>    private val battery: Battery = Battery(batteryLevel = 70)<br><br>    fun useBattery() {<br>        battery.printBatteryLevel()<br>    }<br>}<br><br>//DependentF<br>class Lamp {<br>    private val battery: Battery = Battery(batteryLevel = 60)<br><br>    fun useBattery() {<br>        battery.printBatteryLevel()<br>    }<br>}<br><br>fun main() {<br><br>    val clock = Clock()<br>    val radio = Radio()<br>    val lamp = Lamp()<br><br>    clock.useBattery()<br>    radio.useBattery()<br>    lamp.useBattery()<br>}</pre><p>However, when creating objects in this way, each of our Radio objects (or Clock or Lamp) will be created with batteries of the same level, and for this change, we added the same code to all classes separately. When we do this using Dependency Injection, we will make our changes only in the Battery class at once and add ease of use.</p><pre>//DependencyA<br>class Battery(val batteryLevel: Int) {<br>    fun printBatteryLevel() {<br>        println(&quot;Battery level is $batteryLevel%&quot;)<br>    }<br>}<br><br>//DependentD<br>class Clock(private val battery: Battery) { <br><br>    fun useBattery() {<br>        battery.printBatteryLevel()<br>    }<br>}<br><br>//DependentE<br>class Radio(private val battery: Battery){<br>    <br>    fun useBattery() {<br>        battery.printBatteryLevel()<br>    }<br>}<br><br>//DependentF<br>class Lamp(private val battery: Battery) {<br>   <br>    fun useBattery() {<br>        battery.printBatteryLevel()<br>    }<br>}<br><br>fun main() {<br><br>    val clock = Clock(Battery(80))<br>    val radio = Radio(Battery(70))<br>    val lamp = Lamp(Battery(60))<br><br>    clock.useBattery()<br>    radio.useBattery()<br>    lamp.useBattery()<br>}</pre><p>We saw how easy it is to make changes to the code with manual dependency injection. What if we didn’t have to deal with dependency injection manually and had an assistant to do this in the background while we focused on the functionality of our code? Now let’s look at automated dependency injection.</p><h4>Automated Dependency Injection</h4><p>Using a single dependency does not cause a big problem, if the same class depends on more than one class, manual dependency injection will not be sufficient and will have some disadvantages.</p><blockquote>For big apps, taking all the dependencies and connecting them correctly can require a large amount of boilerplate code. In a multi-layered architecture, in order to create an object for a top layer, you have to provide all the dependencies of the layers below it. As a concrete example, to build a real car you might need an engine, a transmission, a chassis, and other parts; and an engine in turn needs cylinders and spark plugs</blockquote><p>There are libraries that solve this problem by automating the process of creating and providing dependencies.</p><p>We are going to focus to Hilt which is a dependency injection library for Android.</p><h4>Dagger Hilt</h4><p>Hilt or Dagger Hilt provides a standard way to incorporate Dagger dependency injection into an Android application. Actually for the beginners there is a new question:</p><p><strong><em>What is Dagger?</em></strong></p><p><em>Dagger</em> provides a comprehensive and powerful set of tools and features for managing dependencies in Java, Kotlin and Android applications, making it a versatile and widely-used choice for dependency injection.</p><p><strong><em>So why do we choose Dagger Hilt over Dagger?</em></strong></p><p>Dagger Hilt serves as a powerful tool in the realm of Android development, offering a streamlined approach to dependency injection that enhances productivity and code maintainability. Unlike traditional Dagger setups, Hilt abstracts away much of the complexity, providing a more opinionated framework that aligns closely with Android best practices. By simplifying the integration of Dagger into Android applications, Hilt significantly reduces boilerplate code, making the setup process simpler.</p><p>One of the key strengths of Hilt lies in its seamless integration with Android components and<em> Jetpack libraries.</em> It provides built-in support for common Android patterns, such as ViewModel injection, activity, and fragment injection, as well as compatibility with Jetpack’s ViewModel and WorkManager.</p><p>With Hilt, developers can focus more on the functionality of their code, rather than getting bogged down in dependency management. Dagger Hilt is typically used in Android projects for dependency injection in activities, fragments, view models, etc.</p><p>For implementation and more details, you can use <a href="https://developer.android.com/training/dependency-injection/hilt-android">Android Developers Docs</a> as a source, as I did.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d6de0b57057" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrofit vs. Ktor Client]]></title>
            <link>https://medium.com/@gokcensolmaz/retrofit-vs-ktor-client-1c937a827d1b?source=rss-9480b0fee67b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c937a827d1b</guid>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[ktor]]></category>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[ktor-client]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[GokcenYener]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 12:18:45 GMT</pubDate>
            <atom:updated>2024-02-05T12:18:45.363Z</atom:updated>
            <content:encoded><![CDATA[<h3>Navigating the Old Guard and the Newcomer in Android HTTP Requests?</h3><p>When developing an Android application, we use HTTP requests to retrieve data by communicating with the backend. The data we retrieve from the backend via HTTP requests is stored and processed within the application to increase its functionality. To create HTTP requests, Android developers can use frameworks or libraries that implement all the necessary implementations.</p><p>The leading library when it comes to handling HTTP requests is Retrofit. The existence of other frameworks and libraries that can be used besides Retrofit guides us to choose the right tool for our needs. In this article, I will make a comparison between Retrofit, the most used library, and KTor, a Kotlin-focused framework.</p><figure><img alt="Retrofit VS Ktor Client: For Android HTTP Requests" src="https://cdn-images-1.medium.com/max/1024/1*JYrdxT9wY-bnon1BhNXdQg.png" /><figcaption>Retrofit VS Ktor-Client: For Android HTTP Requests</figcaption></figure><p>Retrofit, developed by Square, proved itself due to simplicity and effectiveness in consuming RESTful APIs. Retrofit ensures type safety in the context of HTTP requests and responses. This approach ensures that the compiler can catch type mismatches and inconsistencies at compile time. Retrofit using various serialization libraries such as Gson and Moshi to simplify the process of parsing JSON responses into objects. Its concise syntax and focus on HTTP Client operations makes it more popular.</p><p>Retrofit also supports asynchronous programming. When dealing with network requests, it’s important that these operations are performed asynchronously to prevent blocking the main thread, ensuring that the application remains responsive to user interactions. Retrofit’s approach to asynchronous programming relied on callbacks. When you make a network request, Retrofit allows you to handle the response or error within callbacks (onResponse and onFailure), this way the main thread remains unblocked and the application remains responsive. Over time, Retrofit has evolved to support modern asynchronous programming paradigms, through integration with Kotlin Coroutines. This integration enables developers to make network requests in an easy way with sequential manner and improving code readablitiy and maintainability with avoiding callback complexity.</p><p>Ktor is an open-source, asynchronous, lightweight and flexible framework for building web applications in Kotlin. Positioned as a modern web framework, Ktor enables developers to create strong server-side applications and microservices. Developers can handle both network requests and backend technologies with Ktor. This includes defining routes, adding middleware, and managing complex server logic in a clear way. Ktor comes with built-in support for serialization through kotlinx.serialization, which is developed by JetBrains specifically for Kotlin. So, while Retrofit relies on external libraries for serialization, Ktor leverages its own feature for this purpose. It offers a comprehensive set of tools for building robust server-side components, making it perfect for developers who need a unified platform for both client-side and server-side tasks.</p><p>Additionally, Ktor uses Kotlin’s coroutines for asynchronous programming, making IO operations fast and efficient. Ktor Client supports making requests using suspending functions, which are a fundamental part of Kotlin’s coroutines. This approach allows for more straightforward asynchronous code that is easy to read and write, without the need for additional libraries or adapters to handle asynchronous operations. Ktor’s design approach embraces Kotlin’s coroutine system, making asynchronous programming a core part of its functionality. This native integration with coroutines means that asynchronous code in Ktor is more suitable to Kotlin, providing seamless support for managing concurrent operations and composing asynchronous logic.</p><p>Although Ktor is often known for its server capabilities, it also includes a powerful client library known as Ktor Client. The Ktor Client makes it easy for developers to send HTTP requests, work with web services, and communicate with APIs, through Kotlin’s expressive language features.</p><p>Since Ktor is a multi-platform framework, the Ktor Client uses an engine to handle the requests. To create a Ktor Client on Android, you instantiate it with the “Android” Engine. Different engines support different platforms.</p><p>But Ktor is relatively new and doesn’t have as much strong community as Retrofit, so using Ktor in difficult and complex use cases needs courage as if you are stuck in an unexpected problem, there isn’t much documentation. In other hand, Retrofit has a strong community, loads and loads of documentations and support. However, it’s worth noting that the open-source nature of both tools means that community support can rapidly evolve. JetBrains’ commitment to Ktor does suggest that its documentation and ecosystem will continue to expand, potentially narrowing this gap over time.</p><p>To better illustrate the differences between the two tools in terms of syntax, I will provide code examples that show how to send a GET Request. For this purpose, I’ve selected the API provided by <a href="https://rickandmortyapi.com/">rickandmortyapi.com</a> . I chose this API because I plan to continue using it in my upcoming article, where I’ll discuss libraries for fetching images using the same API.</p><h4>Client Initialization</h4><p><strong>Ktor:</strong> In the heart of utilizing Ktor Client in Android development is initializing the client with the appropriate configurations. The following snippet demonstrates how to instantiate the HttpClient using the Androidengine, which is tailored for Android applications. Additionally, it showcases the installation of the ContentNegotiation plugin with JSON serialization. This setup is crucial for enabling the client to automatically handle JSON data formats, streamlining the process of communicating with web services.</p><pre>private val client = HttpClient(Android) {<br>    install(ContentNegotiation) {<br>        json()<br>    }<br>}</pre><p><strong>Retrofit: </strong>The initialization of the Retrofit client marks the first step in setting up a robust communication with web services in Android development. The code snippet below demonstrates how to create a Retrofit instance. This instance is configured with the base URL of the ‘Rick and Morty API’ and utilizes the Gson converter factory for JSON serialization. This configuration is essential for ensuring seamless conversion of JSON data into Kotlin objects, thereby simplifying the task of data handling in the application.</p><pre>private val retrofit = Retrofit.Builder()<br>    .baseUrl(&quot;https://rickandmortyapi.com/api/&quot;)<br>    .addConverterFactory(GsonConverterFactory.create())<br>    .build()</pre><h4>Making an HTTP Request</h4><p><strong>Ktor: </strong>This function illustrates how to perform a GET request using Ktor Client to fetch a character’s details from the ‘Rick and Morty API’. The function getCharacter takes a character ID as a parameter and returns the character details. This example highlights the simplicity and power of Ktor Client in executing HTTP requests and processing the responses.</p><pre>private suspend fun getCharacter(characterId: String): Character? {<br>    val character = client<br>        .get(&quot;https://rickandmortyapi.com/api/character/$characterId&quot;)<br>    return character.body()<br>}</pre><p><strong>Retrofit: </strong>Defining the interface for HTTP requests is a cornerstone of using Retrofit. The following snippet illustrates how to declare an interface using Retrofit annotations, which describe the HTTP operations. Here, a GET request is defined to fetch a character’s details from the ‘Rick and Morty API’ by specifying the character ID as a dynamic URL path. This approach encapsulates the API endpoints as interface methods, making the code clean, concise, and easy to maintain.</p><pre>interface RickAndMortyApi {<br>    @GET(&quot;character/{id}&quot;)<br>    fun getCharacter(@Path(&quot;id&quot;) characterId: String): Call&lt;Character&gt;<br>}<br><br>...<br><br>class MainActivity : ComponentActivity(){<br>...<br>  private val api = retrofit.create(RickAndMortyApi::class.java)<br>  private fun getCharacter(characterId: String) {<br>      api.getCharacter(characterId).enqueue(object : Callback&lt;Character&gt; {<br>          override fun onResponse(call: Call&lt;Character&gt;, response: Response&lt;Character&gt;) {<br>              if (response.isSuccessful) {<br>                  characterInfoLiveData.postValue(response.body())<br>              }<br>          }<br>  <br>          override fun onFailure(call: Call&lt;Character&gt;, t: Throwable) {<br>              TODO(&quot;Not yet implemented&quot;)<br>          }<br>      })<br>  }<br>...<br>}</pre><h4>Calling the HTTP Request Function</h4><p><strong>Ktor:</strong> The following snippet demonstrates how to invoke the getCharacter function when a user clicks a button. This operation is performed within a coroutine launched by lifecycleScope, which is part of the Android Jetpack&#39;s Lifecycle library. This approach ensures that the network request is made in a non-blocking way, adhering to best practices for asynchronous programming in Android. The runOnUiThread method is then used to update the UI with the fetched data, showcasing a practical application of Ktor Client in a real-world scenario.</p><pre>Button(<br>    modifier = Modifier<br>        .fillMaxWidth()<br>        .padding(16.dp),<br>    onClick = {<br>        lifecycleScope.launch {<br>            val character = getCharacter(characterIdInput)<br>            runOnUiThread {<br>                characterInfoLiveData.value = character<br>            }<br>        }<br>    }<br>) {<br>    Text(text = &quot;Get Character&quot;)<br>}</pre><p><strong>Retrofit:</strong></p><pre>Button(<br>    modifier = Modifier<br>        .fillMaxWidth()<br>        .padding(16.dp),<br>    onClick = {<br>        if (characterIdInput.isNotEmpty()) {<br>            getCharacter(characterIdInput)<br>        }<br>    }<br>) {<br>    Text(text = &quot;Get Character&quot;)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4sMXDhugLZM2kTKnkH_A9A.png" /><figcaption>Application UI Transformation: Before and After Executing a Ktor GET Request to Fetch ‘Rick and Morty’ Character Details.</figcaption></figure><p>In conclusion, Retrofit and Ktor Client offer different advantages for handling HTTP requests in Android applications. The Retrofit stands out for its simplicity, type safety, and strong community support. Although Ktor Client is newer, it has flexibility, Kotlin coroutine-based asynchronous programming, and built-in serialization support. While Retrofit currently has a larger community, Ktor Client’s multiplatform capabilities point to its potential growth. The choice depends on project needs and familiarity with the tools, but both offer solid solutions for efficient networking in Kotlin-based Android development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c937a827d1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>