<?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 Mohammed khudair on Medium]]></title>
        <description><![CDATA[Stories by Mohammed khudair on Medium]]></description>
        <link>https://medium.com/@mohammedkhudair57?source=rss-4593c0843a29------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EmZclMDF531z-KeFX8-nrQ.jpeg</url>
            <title>Stories by Mohammed khudair on Medium</title>
            <link>https://medium.com/@mohammedkhudair57?source=rss-4593c0843a29------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 08:24:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohammedkhudair57/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[Kotlin Scope functions]]></title>
            <link>https://medium.com/@mohammedkhudair57/kotlin-scope-functions-870475a32f05?source=rss-4593c0843a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/870475a32f05</guid>
            <category><![CDATA[kotlin-scope-functions]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Mohammed khudair]]></dc:creator>
            <pubDate>Thu, 12 Jun 2025 13:23:16 GMT</pubDate>
            <atom:updated>2025-06-12T13:30:40.480Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Scope Functions In Android</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dWDxrvNyutuUlwm_wswBdw.png" /></figure><blockquote>“It took me days <strong>and several cups of coffee</strong> to craft this story, so it’s a comprehensive guide packed with examples for each scope function. By the end, you’ll be able to use them with confidence<strong>.</strong></blockquote><h3><strong>Overview</strong></h3><p>Kotlin offers a powerful feature known as <strong>scope functions</strong>, which enhance code readability and maintainability by simplifying object manipulation within a defined scope. These functions provide an elegant way to access and modify objects without explicitly referencing their names.</p><h4><strong>What Are Scope Functions?</strong></h4><p>Well, Kotlin offers five main scope functions — let, run, with, apply, and also—to execute code within an object&#39;s context. When invoked on an object, they allow access to it within their block without using its name. These functions vary in how they provide object access and their return values, making them useful for diverse scenarios.</p><p>Please take a look at this diagram here. Don’t worry, we’ll go over each one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QqY-1qMnxlPkS07sp98xmQ.png" /></figure><h4>What is the point of Scope functions?</h4><p>✅ <strong>Cleaner </strong>✅ <strong>Safer ✅ More Focuse</strong></p><p><strong>Scope functions in Kotlin</strong> simplify object handling by letting you operate within a defined scope without repeating the object’s name.<br> They boost readability and maintainability by grouping related operations and reducing boilerplate code.<br> While they don’t add new features, they make your code cleaner, concise, and more expressive.</p><h3>Get Started with the Functions</h3><h4>Let</h4><p>The let function in Kotlin allows you to perform operations on an object and then return the result of those operations. Inside the let block, you can access the object using it (or a custom name you choose). This is useful for transforming objects or performing calculations on them without affecting the original object.</p><p>It’s also excellent for chaining calls or when you want to introduce a local variable with a limited scope inside let</p><p><strong>Note:</strong> The common use case of let</p><p>let Is your go-to scope function when you need to perform operations on a nullable object and want to ensure those operations only execute if the object is not null, by using the safe call operator ?.</p><p><strong>The context object</strong> is available as an argument it.</p><p><strong>The return value</strong> is the lambda result.</p><h4><strong>Example 1</strong></h4><p><strong>Basic example use case</strong></p><pre>fun main() {<br><br>        val books = listOf(&quot;Atomic Habits&quot;, &quot;Feel Good Productivity&quot;, &quot;Show Your Work&quot;)<br><br>        val bookInfo = books.let { it -&gt;<br>            // &#39;it&#39; is the &#39;books&#39; list here<br>            val numberOfBooks = it.size<br>            val firstBookTitle = it.firstOrNull() <br><br>            &quot;You have $numberOfBooks books. The first one is \&quot;$firstBookTitle\&quot;.&quot;<br>            // Let returns this descriptive string<br>        }<br>        println(bookInfo)<br>    }<br><br>// Output: You have 3 books. The first one is &quot;Atomic Habits&quot;.</pre><p>We uselet to perform calculations or retrieve specific information <em>about</em> the list and return that information.</p><h4>Example 2:</h4><p><strong>For a nullable use case. Using </strong><strong>?.let for Safe Execution</strong></p><pre>fun main() {<br>    val movieTitle: String? = &quot;   Avengers: Endgame   &quot;<br><br>// If movieTitle is not null, the lambda inside let executes.<br>    val formattedTitle = movieTitle?.let { title -&gt;<br>        println(&quot;Original title: \&quot;$title\&quot;&quot;)<br>        title.uppercase()<br>            .trim()<br>            .subSequence(0, 15)//Extracts just the first 15 characters.<br>    }<br>    println(&quot;Formatted title: \&quot;$formattedTitle\&quot;&quot;)<br>}<br><br>// Output: Original title: &quot;   Avengers: Endgame   &quot;<br>//         Formatted title: &quot;AVENGERS: ENDGA&quot;</pre><p>To perform actions on a non-null object, use the safe call operator ?. and call let .</p><h4>Example 3</h4><p><strong>Real-world Scenario</strong>:</p><p>You can take a look at this exam here. We update the user profile UI using Jetpack Compose components.</p><pre>@Composable<br>fun UserProfileScreen(viewModel: ProfileViewModel) {<br>    val user by viewModel.currentUser.collectAsState()<br><br>    Column(modifier = Modifier<br>            .fillMaxSize()<br>            .padding(16.dp),<br>        horizontalAlignment = Alignment.CenterHorizontally<br>    ) {<br>        user?.let { userData -&gt;<br>            // User is not null - show profile<br>            AsyncImage(<br>                model = userData.avatarUrl ?: R.drawable.default_avatar,<br>                contentDescription = &quot;Profile picture&quot;<br>            )<br>            Text(<br>                text = userData.displayName,<br>                style = MaterialTheme.typography.headlineMedium<br>            )<br><br>            userData.bio?.let { bio -&gt;<br>                Text(<br>                    text = bio,<br>                    style = MaterialTheme.typography.bodyMedium,<br>                )<br>            }<br>            <br>            userData.membership?.let {<br>                Badge(<br>                    containerColor = when (it.tier) {<br>                        &quot;PREMIUM&quot; -&gt; MaterialTheme.colorScheme.primary<br>                        &quot;PRO&quot; -&gt; MaterialTheme.colorScheme.tertiary<br>                        else -&gt; MaterialTheme.colorScheme.secondary<br>                    }<br>                ) {<br>                    Text(it.tier)<br>                }<br>            }<br>            <br>        } ?: ShowGuestUi()  // User is null - show guest UI<br>    }<br>}</pre><h4>With</h4><p>The with function in Kotlin is used to execute a block of code within the context of an object, similar to other scope functions. However, unlike let or apply, <strong>with is NOT an extension function</strong>. Instead, you pass the object you want to work with as an argument directly into with(yourObject) { ... }.</p><p><strong>Why and When to Use </strong><strong>with?</strong></p><p>We typically use withwhen:</p><ol><li><strong>You want to perform multiple operations or access many properties on a single object.</strong> Instead of writing object.property1, object.methodA(), object.property2, you can just write property1, methodA(), property2 inside the with block, making your code much more concise and readable. It&#39;s like saying, &quot;With <em>this</em> object, do all these things.&quot;</li><li><strong>You don’t need to use the </strong><strong>with function&#39;s return value for subsequent operations.</strong> While with <em>does</em> return the result of its last expression, its primary purpose isn&#39;t usually about transforming the object and returning a new value (like let). It&#39;s more about grouping actions on an object.</li></ol><p><strong>The context object</strong> is available as a receiver this.</p><p><strong>The return value</strong> is the lambda result.</p><h4>Example 1</h4><p>Send email Ex</p><pre>class Email {<br>    var to: String = &quot;&quot;<br>    var subject: String = &quot;&quot;<br>    var body: String = &quot;&quot;<br>    var isUrgent: Boolean = false<br>fun send() {<br>        println(&quot;Sending email to: $to \n Subject: $subject \n Body: $body&quot;)<br>    }<br>}<br>fun main() {<br>    val email = Email()<br>    <br>    with(email) {<br>        to = &quot;customer@example.com&quot;<br>        subject = &quot;Order Confirmation&quot;<br>        body = &quot;Thank you for your purchase!&quot;<br>        isUrgent = false<br>        send()<br>    }<br>}<br>/* Output: Sending email to: customer@example.com <br>           Subject: Order Confirmation <br>           Body: Thank you for your purchase!<br>*/</pre><h4>Example 2</h4><p>Imagine you want to prepare an object with many properties.</p><pre>data class Person(<br>    var id: Long = 0,<br>    var name: String = &quot;&quot;,<br>    var email: String = &quot;&quot;,<br>    var phone: String = &quot;&quot;,<br>    var address: String = &quot;&quot;,<br>    var dateCreated: Long = 0,<br>    var lastModified: Long = 0,<br>    var isActive: Boolean = true<br>)<br><br>fun main() {<br>    val newPerson = Person()<br><br>    val result = with(newPerson) {<br>        id = 0<br>        name = &quot;Bob Smith&quot;<br>        email = &quot;bob@example.com&quot;<br>        phone = &quot;555-987-6543&quot;<br>        address = &quot;456 Oak Ave, Othertown, OT 67890&quot;<br>        dateCreated = System.currentTimeMillis()<br>        lastModified = System.currentTimeMillis()<br>        isActive = true<br><br>//      Lambda result, if returning something is necessary.<br>        &quot;${saveToFavDatabase(newPerson)} \n Successfully saved&quot;<br><br>    }<br><br>    println(result)<br>}<br><br>fun saveToFavDatabase(newPerson: Person) = newPerson<br><br><br>/*<br> Output:<br> Person(id=0, name=Bob Smith, email=bob@example.com, phone=555-987-6543, address=456 Oak Ave, Othertown, OT 67890, dateCreated=1747916450453, lastModified=1747916450453, isActive=true).<br> Successfully saved<br>*/<br></pre><h4>Example 3</h4><p><strong>Real-world Scenario</strong>: Setting Up AlertDialog</p><pre>class DialogHelper(private val context: Context) {<br>    <br>    fun showDeleteConfirmationDialog(itemName: String, onConfirm: () -&gt; Unit) {<br>        val builder = AlertDialog.Builder(context)<br>        <br>        with(builder) {<br>            setTitle(&quot;Delete Item&quot;)<br>            setMessage(&quot;Are you sure you want to delete &#39;$itemName&#39;?&quot;)<br>            setIcon(R.drawable.ic_warning)<br>            setCancelable(false)<br>            setPositiveButton(&quot;Delete&quot;) { dialog, _ -&gt;<br>                onConfirm()<br>                dialog.dismiss()<br>            }<br>            setNegativeButton(&quot;Cancel&quot;) { dialog, _ -&gt;<br>                dialog.dismiss()<br>            }<br>            create().show()<br>        }<br>    }<br>}</pre><h4>Run</h4><p>The run function in Kotlin is a versatile scope function that essentially <strong>combines the functionalities of </strong><strong>with and </strong><strong>let</strong>. We can also use it on nullable objects, while with cannot.</p><p><strong>Why and When to Use </strong><strong>run?</strong></p><p>run is particularly useful in two main scenarios:</p><ol><li><strong>When you want to perform operations on an object and then compute a return value.</strong> It&#39;s perfect for when your block both &quot;initializes objects and computes the return value&quot; or simply performs multiple steps and yields a final result.</li><li><strong>When you need to execute a block of code where you don’t have a receiver object, but you still want to get a result.</strong> In this case, you can call run directly without a receiver (run { ... }). It acts as a non-extension function block that immediately executes and returns the result of its last expression, often used for setting up temporary variables or executing a complex computation and returning its outcome.</li></ol><p><strong>The context object</strong> is available as a receiver this.</p><p><strong>The return value</strong> is the lambda result.</p><h4>Example 1</h4><p>Initialize an order using run</p><pre>data class Order(<br>    var id: String = &quot;0&quot;,<br>    var item: String? = &quot;0&quot;,<br>    var quantity: Int? = 0,<br>    var status: String = &quot;Pending&quot;<br>)<br><br>fun main() {<br>    val newOrder = Order()<br><br>    // Here, we use this or the object&#39;s property itself, and you can invoke it on a nullable object as well.<br>    val orderConfirmationMessage = newOrder?.run {<br>        id = &quot;M123&quot;<br>        item = &quot;Monitor&quot;<br>        quantity = 2<br>        status = &quot;Confirmed&quot;<br><br>        &quot;Order ${id} for $quantity $item(s) is $status! Expect delivery soon.&quot;<br>    }<br><br>    println(orderConfirmationMessage)<br>}<br><br>// Output: Order M123 for 2 Monitor(s) is Confirmed! Expect delivery soon.</pre><h4>Example 2</h4><p>Using run as a <strong>non-extension</strong> <strong>function</strong> to calculate the discount.</p><pre>fun main() {<br>    val basePrice = 150.0<br>    val loyaltyPoints = 750<br><br>    val finalPrice = run {<br>        // Variables declared within `run` stay local and do not extend to the main function&#39;s scope.<br><br>        val discountRate = when {<br>            loyaltyPoints &gt;= 1000 -&gt; 0.15 // 15% discount for 1000+<br>            loyaltyPoints &gt;= 500 -&gt; 0.10 // 10% discount for 500-999<br>            else -&gt; 0.0 // No discount<br>        }<br><br>        val discountAmount = basePrice * discountRate<br>        val priceAfterDiscount = basePrice - discountAmount<br><br>        // The last expression is the return value of the &#39;run&#39; block<br>        priceAfterDiscount<br>    }<br><br>    println(&quot;Base Price: $basePrice&quot;)<br>    println(&quot;Loyalty Points: $loyaltyPoints&quot;)<br>    println(&quot;Final Price after discount: $finalPrice&quot;)<br>}<br>/* Output:<br> Base Price: 150.0<br>Loyalty Points: 750<br>Final Price after discount: 135.0     */<br></pre><h4>Example 3</h4><p><strong>Real-world Scenario</strong>: Formatting Product Details.</p><pre>// Our simple data class for a product<br>data class Product(val name: String, val price: Double, val inStock: Int)<br><br>@Composable<br>fun ProductDisplayCard(product: Product) {<br>    val displayDetails = product.run {<br>        // We can directly access &#39;name&#39;, &#39;price&#39;, and &#39;inStock&#39; without &#39;product.&#39;.<br><br>     val stockStatusText =<br>        if (inStock &gt; 0) &quot;In Stock: $inStock units&quot;<br>        else &quot;Out of Stock!&quot;<br><br>        // Format the price to two decimal places<br>        val formattedPrice = &quot;%.2f&quot;.format(price)<br><br>        // The last expression in the &#39;run&#39; block<br>        &quot;Name: $name\nPrice: $$formattedPrice\nStatus: $stockStatusText&quot;<br>    }<br><br>    Column(<br>        modifier = Modifier.padding(16.dp) <br>            .background(MaterialTheme.colorScheme.surfaceContainerHigh, MaterialTheme.shapes.medium) // Card background<br>            .padding(16.dp)<br>    ) {<br>        Text(<br>            text = displayDetails,<br>            style = MaterialTheme.typography.bodyLarge,<br>        )<br>    }<br>}<br><br>@Composable<br>fun ProductDisplayCardPreview() {<br>    MaterialTheme {<br>        Column {<br>            ProductDisplayCard(product = Product(&quot;Smartwatch&quot;, 199.99, 15))<br>            ProductDisplayCard(product = Product(&quot;Bluetooth Speaker&quot;, 49.50, 0))<br>            ProductDisplayCard(product = Product(&quot;Gaming Headset&quot;, 75.00, 30))<br>        }<br>    }<br>}</pre><h4>Apply</h4><p>The apply function is a scope function that <strong>returns the original object</strong> after executing a block of code on it. Think of it as saying take this object, apply these changes to it, then give me back the same object.<strong>apply doesn’t return a lambda expression, if we assign it to a variable, it will be the object itself.</strong></p><p>Apply <strong>is the perfect fit when:</strong></p><ul><li><strong>Configuring Objects:</strong> You want to set up multiple properties or call several initialization methods on an object. It’s like saying, “<strong>Apply these settings to this object.</strong>”</li><li><strong>Chaining Operations:</strong> Because apply returns the context object itself; it&#39;s excellent for fluent APIs or for continuing a chain of operations where you need to modify an object in place, and then pass <em>that same modified object</em> along.</li><li><strong>Code Blocks That Don’t Return a Value:</strong> If the main purpose of your block is to perform side effects (like setting properties) and you don’t need a specific return value from the block itself</li></ul><p><strong>The context object</strong> is available as a receiver this.</p><p><strong>The return value</strong> is the object itself.</p><h4>Example 1</h4><p>Configuring an object</p><pre>data class Movie(var title: String = &quot;&quot;, var director: String = &quot;&quot;, var releaseYear: Int = 0, var genre: String = &quot;&quot;)<br><br>fun main() {<br>    val favoriteMovie = Movie().apply {<br>//Now, Thse type of favoritMovie, is the Movie() object<br>        title = &quot;Inception&quot;<br>        director = &quot;Christopher Nolan&quot;<br>        releaseYear = 2010<br>        genre = &quot;Sci-Fi&quot;<br>    }<br>    println(favoriteMovie)<br><br>// Output: Movie(title=Inception, director=Christopher Nolan, releaseYear=2010, genre=Sci-Fi)</pre><h4>Example 2</h4><p>You can use apply in multiple call chains for more complex processing.</p><pre>data class Movie(var title: String = &quot;&quot;, var director: String = &quot;&quot;, var releaseYear: Int = 0, var genre: String = &quot;&quot;)<br><br>fun main() {<br>    val favoriteMovie = Movie().apply {<br>        title = &quot;Inception&quot;<br>        director = &quot;Christopher Nolan&quot;<br>        releaseYear = 2010<br>        genre = &quot;Sci-Fi&quot;<br><br>    }.apply { // This second `apply` receives the *modified* object from the first `apply`<br><br>        saveToFavoriteDatabase(this) // `this` means the object receiver (Movie)<br>        println(&quot;My Favorite Movie is Saved!&quot;)<br>         // Other code goes here...<br>    }<br>}<br><br>fun saveToFavoriteDatabase(favoriteMovie: Movie) {<br>    // Simulate saving the movie to a database<br>}<br>// Output: My Favorite Movie Saved!</pre><h4>Example 3</h4><p>Real-World Scenario: <strong>Style Configuration</strong></p><pre>@Composable<br>fun StyledText() {<br>    val headlineStyle = TextStyle().apply {<br>        fontSize = 24.sp<br>        fontWeight = FontWeight.Bold<br>        color = MaterialTheme.colorScheme.primary<br>        letterSpacing = 1.2.sp<br>        lineHeight = 32.sp<br>        fontFamily = FontFamily.Serif<br>    }<br>    <br>    val bodyStyle = MaterialTheme.typography.bodyLarge.apply {<br>        color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.8f)<br>        lineHeight = 24.sp<br>    }<br>    <br>    Column {<br>        Text(<br>            text = &quot;Custom Headline&quot;,<br>            style = headlineStyle<br>        )<br>        Text(<br>            text = &quot;This is body text with custom styling applied.&quot;,<br>            style = bodyStyle<br>        )<br>    }<br>}</pre><h4>Also</h4><p>The also function in Kotlin is primarily used for <strong>performing side effects</strong> on an object, where the side effect needs access to the object itself, or when you don’t want to shadow the this reference from an outer scope.</p><p><strong>Think of it as: </strong>“and also do the following with the object, but don’t mess with the flow”.</p><p><strong>The context object</strong> is available as an argument it.</p><p><strong>The return value</strong> is the object itself.</p><h4>Example 1</h4><p>Modifying a Book List with Logging</p><pre>fun main() {<br>    val bookTitles = mutableListOf(&quot;Clean Code&quot;, &quot;Refactoring&quot;, &quot;The Pragmatic Programmer&quot;)<br>    bookTitles<br>        .also { println(&quot;Before adding new book: $it&quot;) }<br>        .add(&quot;Domain-Driven Design&quot;)<br><br>    println(&quot;After adding new book: $bookTitles&quot;)<br>}<br>// Output:<br>// Before adding new book: [Clean Code, Refactoring, The Pragmatic Programmer]<br>// After adding new book: [Clean Code, Refactoring, The Pragmatic Programmer, Domain-Driven Design]</pre><h4>Example 2</h4><p>Logging And Debugging</p><pre>data class User(var id: Int=0, var name: String=&quot;&quot;, var email: String=&quot;&quot;)<br>fun main() {<br>    val user = User().apply {<br>        id = 1<br>        name = &quot;Mohammed&quot;<br>        email = &quot;example@gmail.com&quot;<br>    }.also {<br>        println(&quot;User created: ${it.name} id: ${it.id}&quot;)<br>        logUserCreation(it)<br>        validateUser(it)<br>    }<br>}<br><br>    fun logUserCreation(user: User) = println(&quot;`LOG` New user registered: ${user.email}&quot;)<br><br>    fun validateUser(user: User) {<br>        require(user.email.contains(&quot;@&quot;)) { &quot;Invalid email format&quot; }<br>        println(&quot;`VALIDATION` User ${user.id} is valid&quot;)<br>    }<br><br>// Output:<br>// User created: Mohammed id: 1<br>// `LOG` New user registered: example@gmail.com<br>// `VALIDATION` User 1 is valid</pre><h4>Example 3</h4><p><strong>Real-World Scenario: </strong>Chaining Example: Creating, Logging, and Saving a Book</p><pre>val book = Book().apply {<br>    title = &quot;Clean Code&quot;<br>    author = &quot;Robert C. Martin&quot;<br>    pages = 464<br>    isAvailable = true<br>}.also {<br>    println(&quot;Book created: &#39;${it.title}&#39; by ${it.author}&quot;)<br>    bookRepository.save(it) // Save to database or in-memory store<br>    analytics.trackEvent(&quot;BookAdded&quot;, mapOf(&quot;title&quot; to it.title, &quot;pages&quot; to it.pages))<br>}</pre><p>It’s crucial that bookRepository.save(it) receives <strong>the same </strong><strong>Book instance</strong> created by apply. That’s the key advantage of using also,It allows you to perform actions on the exact same object without modifying or breaking the chain.</p><h4>Example 4</h4><p><strong>Real-World Scenario</strong>: Fetching Game Data with also</p><pre>val game = gameApi.fetchGameDetails(gameId)<br>    .also { logger.info(&quot;Fetched game data: ${it.title}&quot;) }       // Log the game<br>    .also { gameCache.save(it.id, it) }                            // Cache it<br>    .also { analytics.trackEvent(&quot;GameViewed&quot;, mapOf(&quot;id&quot; to it.id, &quot;title&quot; to it.title)) } // Track </pre><h3>Bonus</h3><h4>takeIf and takeUnless</h4><p>Beyond the main scope functions, Kotlin’s standard library offers takeIf and takeUnless for embedding state checks directly within call chains.</p><ul><li><strong>takeIf</strong>: Returns the object if it <strong>satisfies</strong> a given condition (predicate); otherwise, it returns null. It acts as a filter for a single object.</li><li><strong>takeUnless</strong>: It’s the opposite logic of takeIf , returns the object if it <strong>does not satisfy</strong> a given condition (predicate); otherwise, it returns nul.</li></ul><p>In both, the object is available as the lambda argument (it).</p><pre>fun main() {<br>    val number = Random.nextInt(100)<br><br>    val evenOrNull = number.takeIf { it % 2 == 0 }<br>    val oddOrNull = number.takeUnless { it % 2 == 0 }<br>    println(&quot;even: $evenOrNull, odd: $oddOrNull&quot;)<br>}<br>// Output:<br>// even: 48, odd: null. <br>Your answer would mostly be different.</pre><p><strong>Note</strong></p><blockquote>When chaining other functions after takeIf and takeUnless, don&#39;t forget to perform a null check or use a safe call (?.) because their return value is nullable.</blockquote><pre>fun main() {<br>    val str = &quot;Hello&quot;<br>    val caps = str.takeIf { it.isNotEmpty() }?.uppercase()<br>    //val caps = str.takeIf { it.isNotEmpty() }.uppercase() //compilation error<br>    println(caps)<br>}<br>// Output:<br>// HELLO</pre><h3>When to Use What</h3><p>It’s very common to feel confused by scope functions at first. The trick is to focus on <strong>what you want to do with the object</strong> and <strong>what you expect back</strong> from the block.</p><p><em>Here’s a simple guide to help you choose.</em></p><p><strong>Ask Yourself These Questions:</strong></p><p><strong>1</strong>. Are you just setting up/configuring an object, and want the <em>same object back</em>?</p><p><strong>Use </strong>apply: This is its primary job.</p><p><strong>2</strong>. Are you performing a <em>side effect</em> (like logging, debugging, adding to a list) <em>with</em> the object, but don’t want to change the main flow or the object’s type?</p><p><strong>Use </strong>also: It&#39;s perfect for non-intrusive operations.</p><p><strong>3</strong>. Is the object <em>nullable</em>, and you want to perform actions <em>only if it’s not null</em>? OR, do you want to <em>transform</em> the object into a <em>different kind of result</em>?</p><p><strong>Use </strong>let: Great for null-safety and when the output of the block is a new value.</p><p><strong>4</strong>. Do you need to perform multiple operations on an object (like with), <strong>AND</strong> you also want to <em>compute and return a specific value</em> from that block, like let ?</p><p><strong>Use </strong>run It&#39;s a combination of with and let (returns a result).</p><p><strong>5</strong>. Are you doing a bunch of things <em>with an object you already have</em>, but don’t intend to chain it further, and maybe you want a simple return from the block?</p><p><strong>Use </strong>with: This is a standalone function where you pass the object as an argument.</p><blockquote>Simplified overview diagram</blockquote><figure><img alt="Simplified overview diagram Image" src="https://cdn-images-1.medium.com/max/1024/1*Ks1PRmvOr0H_Rx99GrKt1g.png" /></figure><h3>Conclusion</h3><p>And that’s our deep dive into Kotlin’s <strong>powerful scope functions</strong>!</p><p>You now have the key concepts of<strong> Scope Functions.</strong> Put them into practice, and feel free to revisit this guide anytime you need a refresher</p><p>So, <strong>next time</strong> you’re crafting Kotlin code, remember the unique strengths of each scope function. Experiment with them, and you’ll likely discover new ways to make your code cleaner and more effective.</p><blockquote><strong>See every challenge as a puzzle waiting to be solved. Enjoy the process</strong>!</blockquote><h3>Follow me on:</h3><p><a href="https://x.com/mohammedkhuda19">X </a>| <a href="https://www.linkedin.com/in/mohammed-khudair-4797b8177/">LinkedIn</a> | <a href="https://www.youtube.com/@AndroidDojo">YouTube</a> | <a href="https://www.instagram.com/androiddojo64/">Instagram</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=870475a32f05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVVM Architectural Pattern in Android]]></title>
            <link>https://medium.com/@mohammedkhudair57/mvvm-architectural-pattern-in-android-617b12537d4c?source=rss-4593c0843a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/617b12537d4c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Mohammed khudair]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 06:54:11 GMT</pubDate>
            <atom:updated>2024-01-28T08:31:23.028Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNlTvPiF7VkcE3BOap6RRA.png" /></figure><h3>Introduction</h3><p>MVVM is a recognized software design pattern that enhances code maintainability by separating the user interface (View) from the brainy business logic (Model) through an intermediary component called the ViewModel. This approach improves testability and reusability. MVVM overcomes the drawbacks of MVP and MVC, providing a clean and structured codebase. It ensures a clear understanding of crucial logic components in Android applications, facilitating feature management.</p><p>With MVVM, understanding what’s happening in our Android app is a breeze, making it a snap to add or remove features. Plus, it’s a team player during <strong>Unit Testing</strong>, ensuring our code gets all the attention it deserves without interference from other classes. Go, MVVM! 🚀✨.</p><h3>What is MVVM?</h3><p>“In simple terms, MVVM stands for <strong>Model-View-ViewModel</strong>. Its primary goal is to enhance the clarity and comprehensibility of our code. MVVM champions testability, maintainability, reusability, and scalability, making it a powerful approach for developing robust and user-friendly applications.”</p><h4>Main Components</h4><ul><li><strong>Model:</strong> represents the data and business logic of the application, typically does not have any direct knowledge of the user interface.</li><li><strong>View: </strong>This layer represents the user interface elements. It focuses on displaying data and handling user interactions without any logic or knowledge about the data itself.</li><li><strong>ViewModel: </strong>Acts as a bridge between the View and the Model. It exposes data to the View through a mechanism like StateFlow, KotlinFlow, or a similar one. It also manages the lifecycle of the data and ensures the View only receives relevant updates.</li></ul><h4>Some Of Its Key features</h4><ul><li><strong>Separation of Concerns: </strong>Here each component has a specific role and responsibility, this enhances reusability and readability, where developers can focus on each component.</li><li><strong>Testability: </strong>Each layer can be tested independently, leading to more robust and reliable apps.</li><li><strong>Maintainability: </strong>MVVM promotes clean and maintainable code by organizing responsibilities into distinct components.</li><li><strong>Scalability:</strong> It is easier to add features or modify existing ones without disrupting the entire application.</li></ul><h3>How does the MVVM work?</h3><p>“The View binds to data exposed by the ViewModel, the ViewModel handles events initiated by the View and communicates with the Model, the Model processes events and manages data storage or retrieval, and the updated data flows back to the View through the ViewModel.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNlTvPiF7VkcE3BOap6RRA.png" /></figure><blockquote>This diagram illustrates communications between the components.</blockquote><h3>Getting started with MVVM</h3><p>Before we get started, it would be awesome if you’re familiar with some cool tools like Coroutine, Hilt, and StateFlow that make our MVVM pattern journey smoother. In this article, I’ll be using Jetpack Compose. Don’t worry if you haven’t explored Jetpack Compose yet — you can easily apply the same ideas to an Activity or Fragment.</p><p>Now let’s set up the necessary components. Let’s kickstart the journey.</p><h4>Project setup</h4><p>for our ViewModel add the following dependencies to your app-level build.gradle file.</p><pre>dependencies {<br>... other dependencies...<br> implementation (&quot;androidx.lifecycle:lifecycle-viewmodel-compose:2.6.2&quot;)<br>}</pre><p>If you are using Hilt make sure to add these dependencies.</p><p>In app-level build.gradle file.</p><pre>plugins {<br> ... other plugins...<br>    id(&quot;com.google.dagger.hilt.android&quot;)<br>    kotlin(&quot;kapt&quot;)<br>}<br><br>... other components ...<br><br>dependencies {<br>... other dependencies...<br>  implementation(&quot;com.google.dagger:hilt-android:2.49&quot;)<br>  kapt(&quot;com.google.dagger:hilt-android-compiler:2.44&quot;)<br>}</pre><p>In project-level build.gradle file.</p><pre>plugins {<br>   ... other plugins...<br>    id(&quot;com.google.dagger.hilt.android&quot;) version &quot;2.44&quot; apply false<br><br>}</pre><p>If you’re not familiar with setting up Hilt, no problem! Check out this simple guide from the <a href="https://developer.android.com/training/dependency-injection/hilt-android#setup">official Hilt doc</a>. It’s simple!👍</p><h4>Define Project Structure</h4><p>Define the project structure based on the separation of concern, typically, you will have separate packages of the components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*YkdUaohVJQUL9PN7dq4n5A.png" /></figure><p>Here’s a glimpse of how I’ve organized my package structure.</p><h4>Let’s start with the “data layer”</h4><p>The data layer is considered as our <strong>Model Component.</strong></p><pre>data class Game(<br>    val id: Int,<br>    val title: String,<br>    val rating: Float,<br>    val review: String<br>)</pre><p>This is our Game class that holds the data info.</p><pre>class GameRepository @Inject constructor() {<br><br>     suspend fun getGames(): List&lt;Game&gt; {<br>         // Fake data fetching, replace this with your actual data source<br>         delay(3000)<br>        return listOf(<br>            Game(1, &quot;The Witcher 3: Wild Hunt&quot;, 4.8f, &quot;A masterpiece of storytelling and open-world design.&quot;),<br>            Game(2, &quot;Red Dead Redemption 2&quot;, 4.9f, &quot;An epic tale of life in America at the dawn of the modern age.&quot;),<br>            Game(3, &quot;Assassin&#39;s Creed Valhalla&quot;, 4.5f, &quot;Explore a dynamic and beautiful open world set against the brutal backdrop of England&#39;s Dark Ages.&quot;),<br>            Game(4, &quot;Cyberpunk 2077&quot;, 4.2f, &quot;An open-world action-adventure story set in Night City, a megalopolis obsessed with power, glamour, and body modification.&quot;),<br>           Game(5, &quot;The Legend of Zelda: Breath of the Wild&quot;, 4.7f, &quot;Step into a world of discovery, exploration, and adventure in The Legend of Zelda: Breath of the Wild.&quot;),<br>           <br>           // Add more games as needed<br>        )<br>    }<br>}</pre><p>“Here, we simulate fetching data from a server or local database just to simplify things and focus on the MVVM concept.”</p><h4>UI Layer</h4><p><strong>The ViewModel</strong> <strong>Component</strong> plays a crucial role as part of the MVVM, where we handle events and reduce the view state. The ViewModel acts as a middleman between the View and the Model.</p><pre>@HiltViewModel<br>class GameViewModel @Inject constructor(<br>    private val repository: GameRepository<br>) : ViewModel() {<br><br>    private val _uiState = MutableStateFlow(GameUiState(loading = true))<br>    val uiState: StateFlow&lt;GameUiState&gt; get() = _uiState<br><br>    fun getGameList() {<br>        _uiState.value = GameUiState(loading = true)<br>        viewModelScope.launch {<br>            try {<br>                val games = repository.getGames()<br>                _uiState.value = GameUiState(loading = false,games = games)<br>            } catch (e: Exception) {<br>                _uiState.value = GameUiState(loading = false, error =e.message?:&quot;Network error&quot; )<br>            }<br><br>        }<br>    }<br>    // Other methods business goes here..<br>}</pre><p>let’s dive into the <strong>View Component</strong> elements<strong>: </strong>Implement the View component responsible for rendering the UI and observing the Model’s state changes.</p><p><strong>GameUiState </strong>This represents the view state on the screen,<br> whether it’s loading or success fetching the data or an error occurs.</p><pre>data class GameUiState (<br>    val loading :Boolean = false,<br>    val games: List&lt;Game&gt; = emptyList(),<br>    val error: String? = null<br>)</pre><p><strong>In the MainActivity</strong> class, I’ve adopted Jetpack Compose, I put the UI design in a separate file GameScreen.</p><pre>@AndroidEntryPoint<br>class MainActivity : ComponentActivity() {<br>    private val viewModel by viewModels&lt;GameViewModel&gt;()<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            MVVM_PatternProjectTheme {<br>                // A surface container using the &#39;background&#39; color from the theme<br>                Surface(<br>                    modifier = Modifier.fillMaxSize(),<br>                    color = MaterialTheme.colorScheme.background<br>                ) {<br>                    GameScreen(viewModel = viewModel)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><strong>GameScreen file</strong></p><pre>// Be careful to add this import for items.<br>import androidx.compose.foundation.lazy.items<br><br>@Composable<br>fun GameScreen(viewModel: GameViewModel) {<br>    val gameUiState by viewModel.uiState.collectAsState()<br><br><br>    LaunchedEffect(viewModel) {<br>        viewModel.getGameList()<br>    }<br><br>    Column(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .padding(16.dp)<br>    ) {<br>        when {<br>            gameUiState.loading -&gt; {<br>                // Display a loading indicator<br>                Box(<br>                    modifier = Modifier.fillMaxSize(),<br>                    contentAlignment = Alignment.Center<br>                ) {<br>                    CircularProgressIndicator(color = Color.Blue)<br>                }<br>            }<br><br>            gameUiState.error != null -&gt; {<br>                // Display an error message<br>                Box(<br>                    modifier = Modifier.fillMaxSize(),<br>                    contentAlignment = Alignment.Center<br>                ) {<br>                    val errorMessage = gameUiState.error<br>                    Text(text = &quot;Error: $errorMessage&quot;, color = Color.Red, fontSize = 18.sp)<br>                }<br>            }<br><br>            else -&gt; {<br>                // Display the list of games<br>                GameList((gameUiState.games))<br>            }<br>        }<br>    }<br><br>}<br><br>@Composable<br>fun GameList(games: List&lt;Game&gt;) {<br>    LazyColumn {<br>        items(games) { game -&gt;<br>            GameListItem(game = game)<br>        }<br>    }<br>}<br><br>@Composable<br>fun GameListItem(game: Game) {<br>    // Display a game item<br>    Card(<br>        modifier = Modifier<br>            .fillMaxWidth()<br>            .padding(8.dp)<br>            .shadow(4.dp, RoundedCornerShape(8.dp))<br>    ) {<br>        Column(<br>            modifier = Modifier.padding(8.dp)<br>        ) {<br><br>            Text(<br>                text = game.title,<br>                style = TextStyle(<br>                    fontSize = 18.sp,<br>                    fontWeight = FontWeight.Bold<br>                )<br>            )<br>            Text(<br>                text = game.review,<br>                modifier = Modifier.padding(4.dp)<br>            )<br>            Text(<br>                text = &quot; Rating: ${game.rating}&quot;,<br>                color = Color.Gray,<br>                style = TextStyle(<br>                    fontWeight = FontWeight.Bold<br>                )<br>            )<br>        }<br>    }<br>}<br><br></pre><p>Here, we’re crafting the UI for GameScreen where we observe data from the ViewModel and manage loading states, errors, and display the games list.</p><p><strong>If you’re still using views it will look something like this:</strong></p><pre>@AndroidEntryPoint<br>class MainActivity : ComponentActivity() {<br>    private val viewModel:GameViewModel by viewModels()<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br><br>      // Observe the state<br>       lifecycleScope.launchWhenStarted {<br>           viewModel.uiState.clolect { uiState -&gt;<br>                    render(uiState)<br>              }<br><br>        // Launch getGamelist fun to update uiState.<br>        viewModel.getGameList()<br>    }<br><br>    override fun render(state: GameUiState) {<br>        // Update UI based on the state<br>        if (state.loading) {<br>            // Show loading indicator<br>        } else if (state.error != null) {<br>            // Show error message<br>        } else {<br>            // Display the list of games<br>            val gameList = state.games.map { it.title }<br>            // Update UI with gameList<br>        }<br>    }<br>}</pre><p>Here’s the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g-Dv3rLNJEZW--SMxxj5uA.png" /><figcaption>An image shows the app result</figcaption></figure><h3>Congratulations 🎉🎆</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZkBr4Fhm7OVGgQHubdpGkg.png" /></figure><p>Remember, the adoption of MVVM is a journey, not a sprint. Start with small, manageable steps, and gradually integrate MVVM into your projects.</p><blockquote>“Discover the joy of exploring! Every adventure is a chance to find something wonderful, learn something new, and transform obstacles into stepping stones toward a future filled with unexpected victories and triumphs.”</blockquote><p>“Stay curious, stay driven, and watch your skills soar. Happy coding!”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=617b12537d4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVI Architecture Pattern in Android]]></title>
            <link>https://medium.com/@mohammedkhudair57/mvi-architecture-pattern-in-android-0046bf9b8a2e?source=rss-4593c0843a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/0046bf9b8a2e</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Mohammed khudair]]></dc:creator>
            <pubDate>Wed, 03 Jan 2024 22:06:38 GMT</pubDate>
            <atom:updated>2024-08-13T01:27:21.349Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="This diagram illustrates the unidirectional data flow" src="https://cdn-images-1.medium.com/max/1024/1*g096nFb3zpzDDiZIJWAEUA.png" /></figure><h3>Introduction</h3><p>The MVI (Model-View-Intent) architecture, a popular approach in Android development, emphasizes clean code and a clear separation of concerns by dividing the application into three main components: Model, View, and Intent. This unidirectional data flow and distinct roles contribute to easier understanding, building, and maintenance of MVI apps. The structure also enhances predictability and testability, resulting in smoother development and fewer bugs. This makes MVI an effective choice for creating scalable and maintainable Android applications.</p><h3>What is MVI?</h3><p><strong>MVI architecture in a nutshell.</strong></p><p>What it is: An architecture pattern offers a well-structured approach for building scalable, robust, and testable Android applications. It promotes clear code and smooth development.</p><h4>Key features:</h4><ul><li><strong>Unidirectional data flow:</strong> means data flows in a single direction — from the Model to the View and back as Intents. This ensures clarity, predictability, and ease of maintenance in the architecture.</li><li><strong>Separation of concerns: </strong>means distinct roles for Model, View, and Intent components. The Model manages the state, the View handles UI rendering, and the Intent captures and communicates user actions.</li><li><strong>Immutability: </strong>ensures that the Model’s state remains unchanged once set. This guarantees predictability, eliminates unexpected side effects, and promotes a stable and reliable application state.</li></ul><h4>Components:</h4><ul><li><strong>Model:</strong> Holds all the app’s data and logic, like a single source of truth. It’s never directly changed, but updated by creating new states.</li><li><strong>View: </strong>View is the UI renderer, displaying the app’s state to the user without handling business logic. It updates based on the Model’s state changes.</li><li><strong>Intent: </strong>Represents user actions or the app itself, like button clicks or text input, it’s all about what the user wants to do in the app. The View catches these intentions and sends them to the Model, which then takes actions (like updating the app’s status)</li></ul><h3>How does the MVI work?</h3><p>User does an action which will be an Intent → Intent is a state which is an input to model → Model stores state and sends the requested state to the View → View Loads the state from Model → Displays to the user. If we observe, the data will always flow from the user and end with the user through intent. It cannot be the other way, Hence it&#39;s called Unidirectional architecture. If the user does one more action the same cycle is repeated, hence it is Cyclic.</p><figure><img alt="This diagram illustrates the unidirectional data flow" src="https://cdn-images-1.medium.com/max/1024/1*v7lNoxxYRmuhArctf87crQ.png" /></figure><blockquote>This diagram illustrates the unidirectional data flow</blockquote><h3>Getting Started with MVI</h3><p>Before we get started, it would be awesome if you’re familiar with some cool tools like Coroutine, Hilt, StateFlow, and ViewModel that make our MVI pattern journey smoother. In this article, I’ll be using Jetpack Compose. Don’t worry if you haven’t explored Jetpack Compose yet — you can easily apply the same ideas to an Activity or Fragment.</p><p>Now let’s set up the necessary components and establish the unidirectional data flow. Let’s kickstart the journey.</p><blockquote>We are trying to achieve this in our Android project, which represent data flow between the layers</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8P1AgZEmh2LlIWOxx0eQw.png" /></figure><p><strong>Project setup</strong></p><p>For our ViewModel lifecycle, add the following dependencies to your app-level build.gradle file.</p><pre> <br>dependencies {<br>... other dependencies...<br> implementation (&quot;androidx.lifecycle:lifecycle-viewmodel-compose:2.6.2&quot;)<br>}</pre><p>If you are using Hilt make sure to include these dependencies.</p><p>In app-level build.gradle file.</p><pre>plugins {<br> ... other plugins...<br>    id(&quot;com.google.dagger.hilt.android&quot;)<br>    kotlin(&quot;kapt&quot;)<br>}<br><br>... other components ...<br><br>dependencies {<br>... other dependencies...<br>  implementation(&quot;com.google.dagger:hilt-android:2.49&quot;)<br>  kapt(&quot;com.google.dagger:hilt-android-compiler:2.44&quot;)<br>}</pre><p>In project-level build.gradle file.</p><pre>plugins {<br>   ... other plugins...<br>    id(&quot;com.google.dagger.hilt.android&quot;) version &quot;2.44&quot; apply false<br><br>}</pre><p>If you’re not familiar with setting up Hilt, no problem! Check out this simple guide from the <a href="https://developer.android.com/training/dependency-injection/hilt-android#setup">official Hilt doc</a>. It’s simple!👍</p><h4><strong>Define Project Structure</strong></h4><p>Define the project structure based on the separation of concerns in the MVI architecture. Typically, you’ll have separate packages for the Components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*w4PXgV5RNma5C8GiuWkAHQ.png" /></figure><p>Here’s a glimpse of how I’ve organized my package structure.</p><h4>Let’s start with the “data layer”</h4><p>The data layer is considered as our model component.</p><pre>data class Movie(<br>    val id: Int,<br>    val title: String,<br>    val year: String,<br>)</pre><p>This is our Movie class that holds the data info.</p><pre>class MovieRepository @Inject constructor(){<br><br>    suspend fun getMovies(): List&lt;Movie&gt; {<br>        // Simulate fetching data from a remote server or database<br>        delay(2000)<br>        return listOf(<br>            Movie(1, &quot;Alita Battle Angel&quot;, &quot;2019&quot;),<br>            Movie(2, &quot;Mortal Engines&quot;, &quot;2018&quot;),<br>            Movie(3, &quot;Avatar The Way of Water&quot;, &quot;2022&quot;),<br>            Movie(4, &quot;Lost in Space&quot;, &quot;2018&quot;)<br>        )<br>    }<br>}</pre><p>“Here, we simulate fetching data from a server or local database just to simplify things and focus on the MVI concept.”</p><h4>UI Layer</h4><p><strong>Intent Component</strong>, which represents the user’s intentions or actions within the application.</p><pre>/** Represent the user interactions like<br> * . button clicks,<br> * . text input<br> * . or fetching data from the server or local DB,  whether initiated by the user or the app itself.<br> */<br>sealed class MovieIntent{<br>    object LoadMovies : MovieIntent()<br>}</pre><p><strong>ViewState Component</strong> Implement the View component responsible for rendering the UI and observing the Model’s state changes.</p><pre>/** Theis represent the view state on the screen,<br> * whether it&#39;s loading or success fetching the data or an error occur.<br> */<br>data class MovieViewState(<br>    val loading: Boolean = false,<br>    val movies: List&lt;Movie&gt; = emptyList(),<br>    val error: String? = null,<br>)</pre><p><strong>The ViewModel</strong> plays a crucial role as part of the MVI, where we handle intents and reduce the view state. The ViewModel acts as a middleman between the View and the Model.</p><pre>@HiltViewModel<br>class MainViewModel @Inject constructor(<br>    private val repository: MovieRepository,<br>) : ViewModel() {<br><br>    private val _state = MutableStateFlow(MovieViewState())<br>    val state: StateFlow&lt;MovieViewState&gt; = _state<br><br>    fun handleIntent(intent: MovieIntent) {<br>        viewModelScope.launch {<br>            when (intent) {<br>                is MovieIntent.LoadMovies -&gt; fetchMovies()<br>                // ... Other Intents goes here...<br>            }<br>        }<br>    }<br><br>    private suspend fun fetchMovies() {<br>        _state.value = _state.value.copy(loading = true, error = null)<br>        try {<br>            val movies = repository.getMovies()<br>            _state.value = MovieViewState(loading = false, movies = movies)<br>        } catch (e: Exception) {<br>            _state.value =<br>                MovieViewState(loading = false, error = e.message ?: &quot;Error fetching movies&quot;)<br>        }<br>    }<br><br>}</pre><p>By incorporating a ViewModel in the MVI architecture, you create a separation of concerns, making the application more modular, testable, and easier to maintain.</p><p><strong>In the MainActivity</strong> class, I’ve adopted Jetpack Compose, I put the UI design in a separate file MovieScreen.</p><pre>@AndroidEntryPoint<br>class MainActivity : ComponentActivity() {<br>    private val viewModel:MainViewModel by viewModels&lt;MainViewModel&gt;()<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            MyMVIprojectTheme {<br>                // A surface container using the &#39;background&#39; color from the theme<br>                Surface(<br>                    modifier = Modifier.fillMaxSize(),<br>                    color = MaterialTheme.colorScheme.background<br>                ) {<br><br>                    MovieScreen(mainViewModel = viewModel)<br>                }<br>            }<br>        }<br>    }<br><br>}</pre><p><strong>MovieScreen file.</strong></p><pre>// Be careful to add this import for items.<br>import androidx.compose.foundation.lazy.items<br><br>@Composable<br>fun MovieScreen(mainViewModel: MainViewModel) {<br>    val state by mainViewModel.state.collectAsState()<br><br>    LaunchedEffect(mainViewModel) {<br>        // Trigger the fetchMovies() when the composable is first launched.<br>        mainViewModel.handleIntent(MovieIntent.LoadMovies)<br>    }<br><br>    Column(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .padding(16.dp)<br>    ) {<br>        when {<br>            state.loading -&gt; {<br>                // Display a loading indicator<br>                CircularProgressIndicator(modifier = Modifier.align(CenterHorizontally))<br>            }<br><br>            state.error != null -&gt; {<br>                // Display an error message<br>                Text(text = &quot;Error: ${state.error}&quot;, color = Color.Red)<br>            }<br><br>            else -&gt; {<br>                // Display the list of movies<br>                MoviesList(movies = state.movies)<br>            }<br>        }<br>    }<br><br>}<br><br>@Composable<br>fun MoviesList(movies: List&lt;Movie&gt;) {<br>    LazyColumn {<br>        items(movies) { movie -&gt;<br>            // Display a movie item<br>            Card(<br>                modifier = Modifier<br>                    .fillMaxWidth()<br>                    .padding(8.dp)<br>                    .shadow(4.dp, RoundedCornerShape(8.dp))<br>            ) {<br>                Text(text = &quot;Movie: ${movie.title}&quot;,<br>                    modifier = Modifier.padding(4.dp))<br>                Text(text = &quot;Date: ${movie.year}&quot;,<br>                    modifier = Modifier.padding(4.dp))<br>            }<br>        }<br>    }<br>}</pre><p>Here, we’re crafting the UI for MovieScreen and where we trigger the intent and manage loading states, errors, and displaying the movie list.</p><p>If you&#39;re still using views it will look something like this:</p><pre>@AndroidEntryPoint<br>class MainActivity : ComponentActivity() {<br>    private val viewModel:MainViewModel by viewModels()<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br><br>       lifecycleScope.launchWhenStarted {<br>           viewModel.state.clolect { state -&gt;<br>                    render(state)<br>              }<br><br>        // Trigger the initial intent to load movies<br>        viewModel.handleIntent(MovieIntent.LoadMovies)<br>    }<br><br>    override fun render(state: MovieViewState) {<br>        // Update UI based on the state<br>        if (state.loading) {<br>            // Show loading indicator<br>        } else if (state.error != null) {<br>            // Show error message<br>        } else {<br>            // Display the list of movies<br>            val movieList = state.movies.map { it.title }<br>            // Update UI with movieList<br>        }<br>    }<br>}</pre><p>This is the result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mE5vghhi3pU3lMUq95l5TA.png" /></figure><h3>Congratulations 🎉🎉</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*HGlDw3IYftGGQWuJX06wbA.gif" /></figure><p>Remember, the adoption of MVI is a journey, not a sprint. Start with small, manageable steps, and gradually integrate MVI into your projects. Enjoy the process of creating cleaner, more maintainable UIs!</p><p>“Stay curious, stay driven, and watch your skills soar. Happy coding!”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0046bf9b8a2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Traits Employers Look for When Hiring Software Engineers]]></title>
            <link>https://medium.com/@mohammedkhudair57/10-traits-employers-look-for-when-hiring-software-engineers-67d0b10db11f?source=rss-4593c0843a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/67d0b10db11f</guid>
            <dc:creator><![CDATA[Mohammed khudair]]></dc:creator>
            <pubDate>Sun, 04 Sep 2022 10:39:24 GMT</pubDate>
            <atom:updated>2022-09-04T10:39:24.626Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N7nIPRSydgYbK33UmPy-8Q.jpeg" /></figure><p><strong>This article by By </strong><a href="https://www.codewars.com/post/10-traits-employers-look-for-when-hiring-software-engineers"><strong>Jake Hoffner</strong></a></p><p><strong>Codewars CEO Jake Hoffner provides 10 valuable traits he looks for in a software engineer.</strong></p><p>So, you want to be a software engineer. You did the work, put in the time, and are ready to pursue one of the most in-demand jobs on the market.</p><p>You may be wondering how to get a job as a software engineer or if you have what it takes to get hired. Aside from impressive technical skills, there are several other traits employers, myself included, seek out when hiring for software engineering positions. Hiring the right software engineers is critical to a company’s success. While testing a potential hire’s coding ability should be the first step in assessing fit, technical skill is only one requisite of the job. There are other skill sets in high demand.</p><p>Aside from strong computer programming fundamentals and a promising professional portfolio, job seekers need to possess a range of soft skills to succeed in software engineering roles. From the perspective of an employer, here are skills employers look for when hiring a 10 software engineer.</p><h3>Passionate</h3><p>A software engineer who is passionate about their work will be 10x more effective than someone who is in it just for the paycheck.</p><p>A passionate programmer may not necessarily consider software development both their job and their hobby, but they often do. They like to explore new technologies and concepts, and are constantly pushing their limits, not because they have to, but because they enjoy the challenge. They will often spend much of their personal time learning technologies they are excited about, and because of this, exhibit steady growth in the work place.</p><h3>Fast Learner</h3><p>State of the art of programming is constantly evolving. Software engineers need to demonstrate that they can pick up new technologies, techniques, and best practices quickly. Once a developer understands the core concepts of programming, they should be able to build off of that knowledge. If a software engineer can’t pick up new programming skills, they aren’t going to last long in the industry. Staying up to date with cutting edge technology is pertinent to a company’s advancement, innovation, and success.</p><h3>Focused</h3><p>A software engineer who understands why they’re doing what they’re doing will stay focused and on task. They are able to prioritize and take time management seriously while working on multiple projects at once.</p><p>Like mentioned above, a software engineer should be generally passionate about their field, but also have the discipline to stay focused on short and long term goals. Hiring managers don’t want software engineers who find themselves on tangents, trying to implement unnecessary technology into the codebase or trying to over-optimize things they’re personally interested but aren’t a high priority for the team.</p><p>‍</p><h3>(Sub-)Domain Expert</h3><p>Most companies are not hiring “generalists”.</p><p>Generalists are developers who have a solid foundation in computer science and a broad knowledge across different types of technologies and computer systems, often with one domain that they know best. For example you may have a generalist web developer who can do both front-end (UI) and back-end (business logic) development.</p><p>Of course, it’s still incredibly important for a software engineer to have solid fundamentals and a strong understanding of their domain, but they should also be an expert on the specific technology subdomain they are being considered for. A web specialist would likely know much more than a web generalist about front-end development, but little to nothing about back-end development.</p><p>While generalists are great utility players, they typically won’t be an expert in niche subject matter. Most companies are looking for specialized talent to fill a certain software engineering role . Advances in development are happening so rapidly that it’s becoming increasingly difficult to be a generalist while also staying on top of the latest developments within a specific domain.</p><p>‍</p><h3>Team Player</h3><p>A software engineer can have exceptional talent, but if they don’t know how to work within a team, they’ll have a hard time keeping a job.</p><p>Programming is a form of reproducible logic and thought, therefore developers will invariably have their own style. When presented with a complex problem, you’ll rarely see two software engineers come up with the same exact solution, or even the same general approach.</p><p>When looking to hire a new software engineer, I watch their code writing process to gauge adaptability and to understand if their unique approach will fit into the team’s collective approach.</p><p>Software engineers should write documentation that helps their colleagues understand their work, and they should be able to present their thoughts and take constructive feedback without taking personal offense. Things like clean code, readable documentation, and using consistent concepts are key parts of being a good team player.</p><p>That being said, software engineers need to show that they can adapt to the standards of a team and write code that everyone can understand. Code should be written in a way that makes logical sense and isn’t overly specific to the programmer’s own unique style of organization and thought. With this, new software engineers need to be able to understand how an existing codebase works and how to responsibly add to the collective work of the team.</p><h3>Communicator</h3><p>Effective communicators are consistently sought after in every position — this isn’t unique to software engineering. That’s because miscommunications are expensive and time consuming.</p><p>Software engineers need to be great communicators to reduce errors, increase efficiency, and save money. Miscommunicated product goals are detrimental the company, clients, or users. What do those three things all directly impact? The bottom line.</p><p>Additionally, many companies work with the Agile framework. Within Agile, professional software engineers are expected to participate in scrum meetings, whiteboards, and pair programming. It’s hard to have productive sessions with poor communication.</p><p>Having employable communication skills doesn’t mean you need to be an extrovert. Good communication skills boil down to your ability to explain the projects you’re working on, ask for help, brainstorm ideas, collaborate with teammates, listen well, and accept constructive criticism.</p><p>Effective communicators aren’t afraid to respectfully speak their minds and engage in problem-solving discussions. Thesae are traits that stand out to a hiring manager and will positively impact your job search.</p><h3>Problem Solver</h3><p>Problem solving is at the core of software engineering. This involves a few things .</p><p>First, software developers need to be able to prove that they can quickly identify the cause of an issue. Next, they need to show determination and efficiency in solving it. This might be a bug with an existing set of code, a scalability problem when there’s an increased demand of a product, a maintainability matter when dealing with increasing complexity of code, etc. Not only does the problem need to be identified efficiently, but the developer must also be able to solve it in a clear and concise way.</p><h3>Craftsperson</h3><p>Great programmers take pride in their craft. They write efficient code that is well thought out and well tested. They sweat the details, while still aware that they need to deliver on time. Craftsmanship is all about the quality of the product.</p><p>There is a big difference between simply being skilled, and executing that skill with creativity and dexterity. Potential employers get excited when an applicant genuinely cares about the craft of software engineering.</p><h3>Ownership</h3><p>A good software engineer doesn’t shy away from ownership. Software engineers that show ownership take responsibility for a project while showing confidence in their abilities. The ability to “own” an assignment means that a software engineer is proactive and needs little supervision.</p><p>Ownership won’t always result in perfection. When things go wrong, software engineers who show strong ownership skills are accountable and take pride in problem solving. Other signs of ownership include showing interest in volunteering for new responsibilities, willingness to gain experience, taking initiative, setting the team up for success, and having growth-oriented career goals.</p><h3>Business Acumen</h3><p>Business acumen is the ability to understand and operate within the business context of your company.</p><p>A software engineer with a working foundation of good business sense knows how their work affects the bottom line and can make decisions accordingly. They are able to see the big picture, identify trends, and articulate the impact of technology decisions on business goals.</p><p>While this skill is more likely to be expected and utilized in more senior positions, it is valuable for all software engineering levels. A software developer who understands the trade-offs between perfect code and business impact will be a huge asset to a company. Pursuit of perfect code costs time and additional expenses. In software development, you need to focus on delivering the product. Work to improve it can come later. The priority should always fall on software solutions that strike a balance between speed, performance, maintainability, and cost.</p><h3>Conclusion</h3><p>Having technical skills is incredibly important to land a job as a software engineer. The software engineer job market is competitive. However, technical skills alone won’t promise a lucrative career path. If you want to be a stand-out software engineer candidate, make sure you consider all of the in demand skills to set you apart from other engineers.</p><p>Ten out of ten times, an employer would rather hire a software engineer who works well with their team, learns quickly, and is ready to hit the ground running than a candidate who is highly skilled but uninterested in adapting, communicates poorly, and shows little interest in the craft.</p><p>‍</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67d0b10db11f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Get Rich (without getting lucky) Naval’s tweetstorm]]></title>
            <link>https://medium.com/@mohammedkhudair57/how-to-get-rich-without-getting-lucky-ea210e83aba2?source=rss-4593c0843a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea210e83aba2</guid>
            <dc:creator><![CDATA[Mohammed khudair]]></dc:creator>
            <pubDate>Fri, 14 Jan 2022 19:14:39 GMT</pubDate>
            <atom:updated>2022-01-14T20:05:43.103Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*U9lu6NBGm0ZZwBVfzy3ogw.jpeg" /></figure><p><a href="https://twitter.com/naval/status/1002103360646823936"><strong>Naval’s tweetstorm</strong></a></p><p><a href="https://podcasts.google.com/feed/aHR0cHM6Ly9uYXZhbC5saWJzeW4uY29tL3Jzcw?ep=14"><strong>Naval’s podcast</strong></a><strong> </strong><br><br>Naval Ravikant is an Indian-American entrepreneur and investor. He is the co-founder, chairman and former CEO of <a href="https://angel.co/"><strong>AngelList</strong></a>. He has invested early-stage in over 200 companies including Uber, FourSquare, Twitter, Wish.com, Poshmark, Postmates, Thumbtack, Notion, SnapLogic, Opendoor, Clubhouse, Stack Overflow, Bolt, OpenDNS, Yammer, and Clearview AI, with over 70 total exits and more than 10 Unicorn companies.</p><h3>His podcast video talks about his tweetstorm.</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F1-TZqOsVCNM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D1-TZqOsVCNM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F1-TZqOsVCNM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcc24b8830d22c83567091008b01d0cb/href">https://medium.com/media/fcc24b8830d22c83567091008b01d0cb/href</a></iframe><h3>His quotes are</h3><blockquote>Seek wealth, not money or status. Wealth is having assets that earn while you sleep. Money is how we transfer time and wealth. Status is your place in the social hierarchy.</blockquote><blockquote>Understand that ethical wealth creation is possible. If you secretly despise wealth, it will elude you.</blockquote><blockquote>Ignore people playing status games. They gain status by attacking people playing wealth creation games.</blockquote><blockquote>You’re not going to get rich renting out your time. You must own equity - a piece of a business - to gain your financial freedom.</blockquote><blockquote>You will get rich by giving society what it wants but does not yet know how to get. At scale.</blockquote><blockquote>Pick an industry where you can play long term games with long term people.</blockquote><blockquote>The Internet has massively broadened the possible space of careers. Most people haven’t figured this out yet.</blockquote><blockquote>Play iterated games. All the returns in life, whether in wealth, relationships, or knowledge, come from compound interest.</blockquote><blockquote>Pick business partners with high intelligence, energy, and, above all, integrity.</blockquote><blockquote>Don’t partner with cynics and pessimists. Their beliefs are self-fulfilling.</blockquote><blockquote>Learn to sell. Learn to build. If you can do both, you will be unstoppable.</blockquote><blockquote>Arm yourself with specific knowledge, accountability, and leverage.</blockquote><blockquote>Specific knowledge is knowledge that you cannot be trained for. If society can train you, it can train someone else, and replace you.</blockquote><blockquote>Specific knowledge is found by pursuing your genuine curiosity and passion rather than whatever is hot right now.</blockquote><blockquote>Building specific knowledge will feel like play to you but will look like work to others.</blockquote><blockquote>When specific knowledge is taught, it’s through apprenticeships, not schools.</blockquote><blockquote>Specific knowledge is often highly technical or creative. It cannot be outsourced or automated.</blockquote><blockquote>Embrace accountability, and take business risks under your own name. Society will reward you with responsibility, equity, and leverage.</blockquote><blockquote>The most accountable people have singular, public, and risky brands: Oprah, Trump, Kanye, Elon.</blockquote><blockquote>“Give me a lever long enough, and a place to stand, and I will move the earth.” <br>- Archimedes</blockquote><blockquote>Fortunes require leverage. Business leverage comes from capital, people, and products with no marginal cost of replication (code and media).</blockquote><blockquote>Capital means money. To raise money, apply your specific knowledge, with accountability, and show resulting good judgment.</blockquote><blockquote>Labor means people working for you. It’s the oldest and most fought-over form of leverage. Labor leverage will impress your parents, but don’t waste your life chasing it.</blockquote><blockquote>Capital and labor are permissioned leverage. Everyone is chasing capital, but someone has to give it to you. Everyone is trying to lead, but someone has to follow you.</blockquote><blockquote>Code and media are permissionless leverage. They’re the leverage behind the newly rich. You can create software and media that works for you while you sleep.</blockquote><blockquote>An army of robots is freely available - it’s just packed in data centers for heat and space efficiency. Use it.</blockquote><blockquote>If you can’t code, write books and blogs, record videos and podcasts.</blockquote><blockquote>Leverage is a force multiplier for your judgement.</blockquote><blockquote>Judgement requires experience, but can be built faster by learning foundational skills.</blockquote><blockquote>There is no skill called “business.” Avoid business magazines and business classes.</blockquote><blockquote>Study microeconomics, game theory, psychology, persuasion, ethics, mathematics, and computers.</blockquote><blockquote>Reading is faster than listening. Doing is faster than watching.</blockquote><blockquote>You should be too busy to “do coffee,&quot; while still keeping an uncluttered calendar.</blockquote><blockquote>Set and enforce an aspirational personal hourly rate. If fixing a problem will save less than your hourly rate, ignore it. If outsourcing a task will cost less than your hourly rate, outsource it.</blockquote><blockquote>Work as hard as you can. Even though who you work with and what you work on are more important than how hard you work.</blockquote><blockquote>Become the best in the world at what you do. Keep redefining what you do until this is true.</blockquote><blockquote>There are no get rich quick schemes. That’s just someone else getting rich off you.</blockquote><blockquote>Apply specific knowledge, with leverage, and eventually you will get what you deserve.</blockquote><blockquote>When you’re finally wealthy, you’ll realize that it wasn’t what you were seeking in the first place. But that’s for another day.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea210e83aba2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>