<?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 Sandy on Medium]]></title>
        <description><![CDATA[Stories by Sandy on Medium]]></description>
        <link>https://medium.com/@moesandar675?source=rss-807db4039814------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*cipRcYRIsni4UHSs</url>
            <title>Stories by Sandy on Medium</title>
            <link>https://medium.com/@moesandar675?source=rss-807db4039814------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 04:08:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@moesandar675/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[Flutter Rendering and Elements: From Widgets to RenderObjects]]></title>
            <link>https://medium.com/h7w/flutter-rendering-and-elements-from-widgets-to-renderobjects-2db88cc861d9?source=rss-807db4039814------2</link>
            <guid isPermaLink="false">https://medium.com/p/2db88cc861d9</guid>
            <category><![CDATA[widget-tree]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Sandy]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 01:47:37 GMT</pubDate>
            <atom:updated>2026-02-19T18:00:21.915Z</atom:updated>
            <content:encoded><![CDATA[<p>Flutter is often explained as <em>“everything is a widget”</em>.<br> That’s true but incomplete.</p><p>If you want to understand <strong>performance</strong>, <strong>rebuilds</strong>, and <strong>state management</strong>, you must understand the <strong>Element Tree</strong>. This article connects the dots between <strong>Widgets</strong>, <strong>Elements</strong>, and <strong>RenderObjects</strong>, and explains why most Flutter performance issues are actually <em>Element problems</em>.</p><h3>Guiding Questions</h3><ul><li>What exactly is an <strong>Element</strong>, and how does the Element Tree work?</li><li>What does Flutter consider <strong>expensive rendering</strong>?</li><li>What are the real roles of <strong>Widget</strong>, <strong>Element</strong>, and <strong>RenderObject</strong>?</li><li>Why is <strong>state management in Flutter fundamentally about </strong>controlling how and when Elements rebuild?</li></ul><h3><strong>Render Objects and Widgets</strong></h3><p>In Flutter, some widgets do more than describe UI , they <strong>create RenderObjects</strong>, which are responsible for layout, painting, and hit-testing.These widgets sit lower in the widget tree and subclass one of the following:</p><ul><li><strong>LeafRenderObjectWidget</strong> → No children, just draw (e.g., Image, RawImage, CustomPaint, Texture).</li><li><strong>SingleChildRenderObjectWidget</strong> → One child, modifies rendering (e.g., Align, Padding, Transform, SizedBox).</li><li><strong>MultiChildRenderObjectWidget</strong> → Multiple children, layout rules (e.g., Row, Column, Stack, Wrap, Flex).</li></ul><p>This means a widget like Image ultimately creates a <strong>LeafRenderObject</strong> in the RenderObject Tree.</p><p>RenderObjects are where <strong>constraints</strong>, <strong>layout</strong>, and <strong>painting</strong> actually happen. If you dive into the RenderObject class, you’ll see methods like performLayout() and paint()this is where pixels are decided.</p><p>Example Hireachy</p><pre>Column<br>│<br>├──▶ MultiChildRenderObjectWidget<br>│<br>├── Padding<br>│ │<br>│ └──▶ SingleChildRenderObjectWidget<br>│<br>│ └── Text(&quot;Hello&quot;)<br>│ │<br>│ └──▶ LeafRenderObjectWidget<br>│<br>└── Text(&quot;World&quot;)<br> │<br> └──▶ LeafRenderObjectWidget</pre><p>At this point, we understand <em>what</em> RenderObjects are.<br> To understand <strong>performance</strong>, we need to understand <strong>how they are created and reused</strong>.</p><h3>Understanding Expensive Rendering in Flutter</h3><p>When Flutter renders UI, it’s important to distinguish <strong>widget rebuilds</strong> from <strong>render object recreation</strong>.</p><ul><li><strong>Widgets are lightweight and immutable</strong>. Rebuilding them is cheap.</li><li><strong>RenderObjects are heavy and long-lived</strong>. Creating new ones is expensive.</li></ul><p>Let’s look at two examples:</p><pre><strong>if</strong> (isTrue) Text <strong>else</strong> Container()-- <strong>eg 1</strong><br><strong>if</strong> (isTrue) Container(color : red) <strong>else</strong> Container (color: black) ____<strong>eg2</strong></pre><h3>Example 1 : Expensive</h3><p>When isTrue changes, the widget type changes (Text ↔ Container).<br> Flutter <strong>cannot reuse</strong> the existing Element or RenderObject.</p><p>Result:</p><ul><li>Old Element is unmounted</li><li>Old RenderObject is destroyed</li><li>New RenderObject is created</li></ul><p>This is <strong>expensive rendering</strong>.</p><h3>Example 2 : Efficient</h3><p>The widget type stays the same (Container).<br> Only a property (color) changes.</p><p>Result:</p><ul><li>Same Element reused</li><li>Same RenderObject reused</li><li>Only updateRenderObject() is called</li></ul><p>This is <strong>cheap and efficient rendering</strong>.</p><p>Flutter supports both patterns, but understanding the difference lets you write UI code that scales without performance surprises.</p><h3>Role of Elements in Flutter</h3><p>So far, we’ve talked about Widgets and RenderObjects.<strong>Elements are the missing link between them.</strong></p><p>An <strong>Element</strong>:</p><ul><li>Manages a widget’s lifecycle</li><li>Holds its position in the tree</li><li>Connects a widget to a RenderObject (directly or indirectly)</li></ul><p>At the core:</p><pre>abstract class Element implements BuildContext {<br>  ...<br>}</pre><p>Yes, <strong>Element <em>is</em> BuildContext</strong>!!If you’ve seen these terms before, they all belong to Elements:</p><pre><strong>mounted → whether the element is attached to the tree.<br><br>dirty → marks that the widget needs rebuilding in the next frame.<br><br>BuildOwner → manages dirty elements and triggers rebuilds.</strong></pre><p>That common error:</p><blockquote>“Looking up a deactivated widget’s ancestor is unsafe”</blockquote><p>Simply means: <strong>this Element is no longer mounted in the tree</strong>.</p><h3>How Rebuild Works</h3><p>When Flutter runs a build, it traverses the <strong>element tree</strong> in an <strong>O(N)</strong> way (visiting each node).</p><ul><li>If a widget needs rebuilding, the element is marked <strong>dirty = true</strong>.</li><li>On the next frame, Flutter rebuilds only those dirty elements.</li><li>After rebuild, dirty is reset to <strong>false</strong> so it won’t rebuild again unnecessarily.</li></ul><pre>setState()<br>  ↓<br>markNeedsBuild()        ← sets dirty = true<br>  ↓ <strong>(next frame)</strong><br>performRebuild()<br>  ↓<br>build()                 ← creates NEW widgets<br>  ↓<br><strong>updateChild()  </strong>         ← reconciles element tree<br>  ↓<br>RenderObject updates    ← maybe layout/paint</pre><p>Important :</p><pre>- dirty only means widget rebuild is needed<br>- It does not automatically mean layout or paint<br>- updateChild() decides whether Elements and RenderObjects can be reused</pre><p>Marking elements dirty is cheap and can happen often.<br>Actual reconciliation is deferred to the next frame so Flutter can <strong>batch and optimize work</strong>.</p><h3>Types of Elements</h3><p>There are two major categories:</p><h3>1. ComponentElements</h3><p>These manage widgets that produce other widgets.</p><ul><li>StatelessElement</li><li>StatefulElement</li><li>InheritedElement</li></ul><p>They call build() and produce child widgets.</p><h3>2. RenderObjectElements</h3><p>These manage RenderObjects directly.</p><ul><li>LeafRenderObjectElement</li><li>SingleChildRenderObjectElement</li><li>MultiChildRenderObjectElement</li></ul><p>Important Note:</p><blockquote><em>All UI eventually ends in </em><strong><em>RenderObjectElements</em></strong><em>, because something must paint pixels.</em></blockquote><p>But:</p><ul><li>Not all ComponentElements directly create RenderObjects</li><li>Many exist only to manage rebuild logic</li></ul><h3>Summary</h3><p>When we talk about <em>widget lifecycle</em>, what we’re really describing is the <strong>Element lifecycle</strong>.Widgets are just configuration.RenderObjects do the heavy work.<br><strong>Elements decide what lives, what rebuilds, and what gets reused.</strong></p><p>This is why:</p><blockquote><strong><em>State management in Flutter is fundamentally about </em></strong>controlling how and when Elements rebuild.</blockquote><p>setState, Provider, Riverpod, Bloc — they don’t manage widgets or render objects.<br> They control <strong>which elements rebuild, when, and how often</strong>.</p><p>But Some things in Flutter don’t create RenderObjects at all . For example Navigator. They exist purely to manage structure and state, not pixels.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2db88cc861d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/h7w/flutter-rendering-and-elements-from-widgets-to-renderobjects-2db88cc861d9">Flutter Rendering and Elements: From Widgets to RenderObjects</a> was originally published in <a href="https://medium.com/h7w">T3CH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Cubit ?]]></title>
            <link>https://medium.com/@moesandar675/getting-started-with-cubit-ba13891dce9e?source=rss-807db4039814------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba13891dce9e</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[cubit]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Sandy]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 18:02:56 GMT</pubDate>
            <atom:updated>2025-08-28T18:02:56.943Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting Started with Cubit ?</h3><p>What you will learn in this ?</p><p>This article assumes you already practicing Flutter and have basic programming experience. It’s not a deep dive into Bloc — instead, think of it as a <strong>cheat sheet to get started with Cubit</strong>. We’ll focus only on <strong>how to update state in the UI using Cubit</strong>, and we’ll also look at the different Bloc builders (BlocBuilder, BlocSelector) since they work the same way with both Cubit and Bloc.</p><p>Open your VS Code Terminal and run these two command</p><pre>flutter pub add flutter_bloc<br>flutter pub add equatable<br>flutter pub get</pre><p>Lets start with State Class . There are two way to write states in Cubit and Different people prefer different types . They both have their Pros and Cons.</p><p>Type 1 .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76338d308d0b7a8cd7a1fd5dbd6736b3/href">https://medium.com/media/76338d308d0b7a8cd7a1fd5dbd6736b3/href</a></iframe><p>Type 2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72a9f04b803263b3c8a9eed528993116/href">https://medium.com/media/72a9f04b803263b3c8a9eed528993116/href</a></iframe><p><strong>Type 1 (single state class + flags/nullable fields)</strong>:</p><ol><li>Less boilerplate.</li><li>All values live in one class → changes just copy the old object with updates.</li><li>You must allow null or defaults, since not all fields apply in every case.</li><li>As long as one state class has fewer than ~20 fields, performance impact is negligible.</li></ol><p><strong>Type 2 (abstract + multiple state classes):</strong></p><ol><li>More boilerplate.</li><li>Each state carries only what it needs (Loading has nothing, Success has data, etc.).</li><li>More human-readable → by looking at state classes, you instantly know possible UI states.</li></ol><p>✅ So:</p><p>Choose Type 1 for quick/simple flows or for small projects.</p><p>Choose Type 2 for clarity and long-term maintainability</p><p>Now lets start with Cubit. This is where we will be writing <strong>business </strong>logic .</p><p>Cubit of Type 1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6326e894219ff8c993f69299558f1303/href">https://medium.com/media/6326e894219ff8c993f69299558f1303/href</a></iframe><p>Type 2 .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2a60f6e94168e901e7a51c143afb40e/href">https://medium.com/media/a2a60f6e94168e901e7a51c143afb40e/href</a></iframe><p>As you can see, the Type 2 Cubit is cleaner and simpler since we directly emit specific states without juggling <strong>nullable </strong>fields or flags.</p><p>Also note that you can trigger initial API calls inside the Cubit constructor by emitting a state right after initialization.</p><p><strong>Let’s start with a simple Login UI. Instead of diving into every widget, here’s a quick grouped list to make things easier to understand:</strong></p><p><strong>Layout &amp; Structure (single-child containers)</strong></p><p>. Container, Padding, Center, SafeArea, SingleChildScrollView</p><p><strong>Layout &amp; Structure (multi-child containers)</strong></p><p>Row, Column, ListView, ExpansionTile, Card, SliverAppBar, Scaffold</p><p><strong>Input &amp; Interaction</strong></p><p>TextFormField, ElevatedButton, InkWell, Ink ,</p><p><strong>App Wrappers</strong></p><p>MaterialApp, CupertinoApp</p><p>This grouping helps you quickly see which widgets control layout, which handle input, and which wrap your app.Play with these widgets and its enough to get started with UI.</p><p>Type 1 Login Screen</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/808aad99de5c31d68ac493ca8a5e6fcb/href">https://medium.com/media/808aad99de5c31d68ac493ca8a5e6fcb/href</a></iframe><p>Type 2 Login</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf736a9f5cd52a3d1dd823f83420cfb0/href">https://medium.com/media/cf736a9f5cd52a3d1dd823f83420cfb0/href</a></iframe><p>In both Type 1 and Type 2 we build the UI with BlocBuilder — Type 1 checks state.isLoading == true, while Type 2 checks state is LoginLoading. Calling Cubit functions is the same in both cases. The difference comes with TextEditingController: in Type 1 it’s outside the <strong>builder </strong>(safe), while in Type 2 it’s inside the builder (can reset on rebuild). A cleaner alternative is to keep <strong><em>the controllers inside the Cubit </em></strong>and access them with context.read&lt;LoginCubit&gt;().usernameController.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30f171b79afc1fef4c6aa9ab9aedfa70/href">https://medium.com/media/30f171b79afc1fef4c6aa9ab9aedfa70/href</a></iframe><p>TextEditingController is managed by the Cubit, not the UI.</p><p>UI stays clean (StatelessWidget).Lifecycle handled (dispose() in cubit).</p><p>When it comes to Flutter, the most important thing is <strong>how state updates the UI and which parts get rebuilt</strong>.</p><p>BlocBuilder rebuilds every time a <strong>new state</strong> is emitted. That means even if only one field changes, the whole widget tree inside BlocBuilder gets rebuilt.But what if you just want to toggle a <strong>checkbox</strong>? Do you really want to rebuild the entire TextField and Button too?</p><p>That’s where BlocSelector shines.</p><p>BlocSelector listens to just <strong>one field</strong> of the state.It rebuilds only the widget that depends on that field, not the whole tree.</p><p>In <strong>Type 2</strong> (multiple small states), you avoid some of this because each state represents one scenario.</p><p>In <strong>Type 1</strong> (one big state with many fields), using BlocSelector is super important so you don’t rebuild everything unnecessarily.</p><p>⚡ <strong>Pro tip</strong>: If you’re new to Flutter and want to see rebuilds in action, just add a print(&quot;WidgetName rebuilt&quot;) inside every build method. You’ll instantly see how often and which widgets are being rebuil</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b51c412f443436bb4f0d63f4070ce283/href">https://medium.com/media/b51c412f443436bb4f0d63f4070ce283/href</a></iframe><p>One of the most important how are you providing the cubit ,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39879174d8af2f47f0784c0bc4a0e430/href">https://medium.com/media/39879174d8af2f47f0784c0bc4a0e430/href</a></iframe><p>In this example, the BlocProvider creates the cubit inside MyApp. This means that by the time we reach the <strong>LoginScreen</strong>, the cubit is already available in the widget tree, and you can access it directly with context.read.</p><p>Remember: <strong>where you create a cubit (or any object) defines its lifecycle</strong>.</p><ol><li>If you provide a cubit in <strong>Screen A</strong> and then push <strong>Screen B</strong> on top of it, the cubit from Screen A will continue to live as long as Screen A stays in the navigation stack.</li><li>If you pop back from <strong>Screen B</strong> to <strong>Screen A</strong>, the instance of Screen B (and its cubit) is destroyed.</li></ol><p>I’ve tried to cover the basics of Cubit here, but there’s much more you can explore: adding coding rules, using BlocListener, streams, bloc. I’ll dive into those in my next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba13891dce9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Jetpack Compose UI Testing: A Beginner’s Guide (Part 1)]]></title>
            <link>https://medium.com/@moesandar675/getting-started-with-jetpack-compose-ui-testing-a-beginners-guide-part-1-4ad06ae8cfb3?source=rss-807db4039814------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ad06ae8cfb3</guid>
            <category><![CDATA[ui-testing]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Sandy]]></dc:creator>
            <pubDate>Thu, 08 May 2025 09:52:16 GMT</pubDate>
            <atom:updated>2025-05-08T09:52:16.984Z</atom:updated>
            <content:encoded><![CDATA[<h3>📘 What You’ll Learn</h3><ul><li>✅ How to set up Jetpack Compose UI testing in your project</li><li>🧪 How to write your first simple Compose UI test</li><li>💡 Why UI tests are important and how they save time and effort.</li></ul><h3>Step 1: Set Up the Testing Environment</h3><p>Add these dependencies to your build.gradle (app-level):</p><pre>androidTestImplementation &quot;androidx.compose.ui:ui-test-junit4:1.8.0&quot;<br>debugImplementation &quot;androidx.compose.ui:ui-test-manifest:1.8.0&quot;</pre><blockquote><em>🔍 To get the latest versions, search on </em><a href="https://search.maven.org/"><em>Maven Central</em></a><em> .eg : </em><a href="https://central.sonatype.com/artifact/org.jetbrains.compose.ui/ui-test-junit4"><em>link</em></a></blockquote><p>These dependencies are used to test Jetpack Compose UI.</p><ul><li>ui-test-junit4 Provides the test rule and assertions for Compose UI.</li><li>ui-test-manifest Needed to run UI tests on a device/emulator.</li></ul><h3>Step 2: Sync the Project</h3><p>After adding the dependencies, sync your Gradle project.</p><h3>Step 3: Write Your First Test</h3><p>Let’s create a simple composable and test it.</p><h4>1. Create a Composable</h4><pre>@Composable<br>fun TestGreeting() {<br>    Text(&quot;Hello, Android!&quot;)<br>}</pre><h4>2. Create a Test File</h4><p>Create a new file named TestGreetingTest.kt under src/androidTest.</p><p>Then write the following test:</p><pre>@ExperimentalCoroutinesApi<br>@RunWith(AndroidJUnit4::class)<br>class TestGreetingTest {</pre><pre>// 1. set rule <br>// 2. write test function</pre><pre>   @get:Rule<br>    val composeTestRule = createComposeRule()</pre><pre>    @Test<br>    fun greeting_is_Displayed() {</pre><pre>// we are using the setContent here as usual.</pre><pre>        composeTestRule.setContent {<br>            TestGreeting()<br>        }</pre><pre>        // Check if the text is displayed<br>        composeTestRule.onNodeWithText(&quot;Hello, Android!&quot;).assertIsDisplayed()<br>    }<br>}</pre><p>✅ Boom! You’ve written your first Compose UI test. Now run it!</p><p><strong>Click the run arrow ▶️ to execute your first test.</strong><br> Watch your device — the UI will flash on screen for just a second as the test runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*0vI9tN7Dh3qHwQNzZdwkQg.png" /></figure><h3>Why Write Tests?</h3><p>Let’s say you’re testing a login screen manually:</p><ul><li>Launch the app.</li><li>Enter the correct credentials → ✅ success case.</li><li>Enter incorrect credentials → ❌ error case.</li></ul><p>This process is slow and repetitive. With tests, you can automate it:</p><h4>Example Test Scenarios</h4><ol><li>Launch login screen → type correct password → check for success.</li><li>Launch login screen → type wrong password → check for error.</li></ol><p>Once written, you can run all your tests with a single click. This saves time, ensures accuracy, and makes your app more robust.</p><p>🎉 <strong>That’s it — you’ve just written and run your first Jetpack Compose UI test!</strong><br> In the next part, we’ll dive into testing real features like login flows with user input and UI assertions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ad06ae8cfb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Kotlin Delegation]]></title>
            <link>https://medium.com/@moesandar675/mastering-kotlin-delegation-d7351da081fb?source=rss-807db4039814------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7351da081fb</guid>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin-delegates]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-native]]></category>
            <dc:creator><![CDATA[Sandy]]></dc:creator>
            <pubDate>Wed, 07 May 2025 11:31:08 GMT</pubDate>
            <atom:updated>2025-05-07T11:33:58.680Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is Delegation?</strong></p><p>In simple terms, <strong>delegation</strong> means <strong>assigning a task to someone else</strong>. <br>In Kotlin, delegation is a powerful concept that allows one class to hand off responsibilities to another.</p><p>There are two main types of delegation in Kotlin:</p><ol><li><strong>Interface Delegation</strong></li><li><strong>Property Delegation</strong></li></ol><p><strong>Interface Delegation</strong></p><p>Let&#39;s say we have a team with a team leader, Logger and two team members, Simple Logger and ApplicationLogger. The Logger Team is responsible for a task print.</p><pre>interface Logger {<br>    fun print(tag: String, any: Any)<br>}<br><br>class SimpleLogger : Logger {<br>    override fun print(tag: String, any: Any) {<br>        println(&quot;$tag, ${any.toString()}&quot;)<br>    }<br>}<br><br>// Delegation in action<br>class ApplicationLogger(delegate: Logger) : Logger by delegate</pre><pre>fun main() {<br>// Application Logger is bein created using SimpleLogger delegate)<br>    val mynewLog= ApplicatoinLogger(SimpleLogger()) <br>// ApplicationLogger instance is using SimpleLogger Print<br>    mynewLog.print(&quot;tag&quot;,&quot;hello delegates&quot;)<br>}</pre><p>“Hey <strong>SimpleLogger</strong>, you’ve done this before — I’ll just <strong>delegate</strong> this task to you!”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4d6f789L8edpX9iaWA10Nw.png" /><figcaption>Application Logger print is using Simple Logger print method</figcaption></figure><p>We did not need to write another print method in the ApplicationLogger class. We use the print method of SimpleLogger. To do this, first, we clarify, we will use a delegate in ApplicationLogger. In the parameter ( it said a Logger class will be used) , <strong>by delegate</strong>: The logger class will be responsible for the print function.</p><pre>class ApplicationLogger(delegate: Logger) : Logger by delegate</pre><p><strong>Property Delegation</strong></p><p><strong><em>1. Lazy Delegation</em></strong>: assigning the task of declaring an object using lazy.</p><p>Let’s assume lazy as the person who has the key to a box. This box contains tools(codes to create objects) and objects. He will create the object when it is asked to be created or give the objected if it is already created.</p><pre>//messaage object creation is assign to lazy <br>val message: String by lazy {<br>    println(&quot;Initializing message...&quot;)<br>    &quot;Hello from delegated property!&quot;<br>}<br><br>fun main() {<br>    println(&quot;Before accessing message&quot;)<br>    println(message)  // First access triggers initialization<br>    println(message)  // Second access uses cached value<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dTNKssVac9QLg6DfXF3LmA.png" /><figcaption>First access, Lazy will create the object and give it. Second access, Lazy will check the box, and give the created item.</figcaption></figure><p><strong><em>2. Observable Delegates</em></strong></p><p>Assume there is a room with CCTV . Whenever a new person comes into the room, we want to take some action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W58xHmuY1aXM0wZN-MHVSQ.png" /><figcaption>observing a variable when value is updated</figcaption></figure><pre>var counter: Int by Delegates.observable(0) <br>// in this lambda write the action you need to do when change occur.<br>{ property, oldValue, newValue -&gt; <br>    println(&quot;Property &#39;${property.name}&#39; changed from $oldValue to $newValue&quot;)<br>}<br><br>fun main() {<br>    counter = 5<br>    counter = 10<br>}<br></pre><p>In the code, we create an int variable with “ by Delegates.obserbale(0)” which means the variable&#39;s initial value is 0 and we want to observe it if it changes. When changes occur, print this line for me.</p><p>Summary</p><p><strong>When to Use Kotlin Delegation</strong></p><p><strong>🔹 Interface Delegation</strong></p><p>Use when multiple classes share methods. <strong>Example</strong>: A logger class can delegate printing functionality to another class.</p><p><strong>🔹 lazy Property Delegation</strong></p><p>Use for heavy objects that should be initialised only when needed. <strong>Example</strong>: Lazy load a database connection or large data.</p><p><strong>🔹 observable Property Delegation</strong></p><p>Use to monitor and react to changes in a property’s value. <strong>Example</strong>: Update UI or log changes when a value is modified.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7351da081fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>