<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Rishabh Gupta</title>
    <description>The latest articles on DEV Community by Rishabh Gupta (@rishabhtech94).</description>
    <link>https://dev.to/rishabhtech94</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1363352%2Fdde07f42-5a68-4dbd-abb6-6aaa65e0508c.jpeg</url>
      <title>DEV Community: Rishabh Gupta</title>
      <link>https://dev.to/rishabhtech94</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rishabhtech94"/>
    <language>en</language>
    <item>
      <title>Mastering State Management in Jetpack Compose: A Fun Guide</title>
      <dc:creator>Rishabh Gupta</dc:creator>
      <pubDate>Sun, 24 Mar 2024 15:54:07 +0000</pubDate>
      <link>https://dev.to/rishabhtech94/mastering-state-management-in-jetpack-compose-a-fun-guide-5d5</link>
      <guid>https://dev.to/rishabhtech94/mastering-state-management-in-jetpack-compose-a-fun-guide-5d5</guid>
      <description>&lt;p&gt;&lt;strong&gt;W&lt;/strong&gt;elcome to the world of Jetpack Compose, where building beautiful and interactive UIs for Android apps has never been easier. But as you dive deeper into Compose, you’ll encounter the need for managing state — the data that drives your UI.&lt;/p&gt;

&lt;p&gt;In this article, I’ll explore two powerful tools for managing state: State and StateFlow.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2htq4yu4ris8ujrppad5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2htq4yu4ris8ujrppad5.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;But fear not, I’ll keep things fun and engaging with few examples along the way!&lt;/p&gt;

&lt;p&gt;**&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding State
&lt;/h2&gt;

&lt;p&gt;**&lt;/p&gt;

&lt;p&gt;State represents data that can change over time, directly influencing the UI. In Jetpack Compose, the State class is your go-to solution for managing such dynamic data within a composable function. When the value of a State changes, Compose automatically triggers recomposition, updating the UI accordingly.&lt;/p&gt;

&lt;p&gt;Lets see the working with a small example.&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;Dynamic Text Color *&lt;/em&gt; with State Let’s create a fun example where the color of a text changes dynamically using State.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

@Composable
fun DynamicTextColor() {
    var isRed by remember { mutableStateOf(true) }

    val textColor = if (isRed) Color.Red else Color.Blue

    Button(onClick = { isRed = !isRed }) {
        Text(text = "Click to change color", color = textColor)
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy6rgkg6csyx1qdnpz3mn.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy6rgkg6csyx1qdnpz3mn.jpeg" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;WHAT ?? CONFUSED !!!!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Lets take another small example to better understanding.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lets take an example of the AMAZON app&lt;/strong&gt;, managing the state of the user’s shopping cart is essential.&lt;/p&gt;

&lt;p&gt;You can use _State&amp;gt; _to represent the items in the cart. When the user adds or removes items from the Amazon’s cart, you update the state accordingly, triggering UI updates to display the updated list of items in the cart.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fydc2qvgu793r85px0rbv.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fydc2qvgu793r85px0rbv.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;


@Composable
fun ShoppingCart() {
    val cartItems = remember { mutableStateOf(emptyList&amp;lt;Item&amp;gt;()) }

    Column {
        // Display cart items
        cartItems.value.forEach { item -&amp;gt;
            CartItemRow(item)
        }
        // Add item button
        Button(onClick = { /* Add item to cart */ }) {
            Text("Add Item")
        }
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;**&lt;/p&gt;

&lt;h2&gt;
  
  
  What is StateFlow?
&lt;/h2&gt;

&lt;p&gt;**&lt;br&gt;
While State is great for managing state within a composable, StateFlow is more suitable for managing state outside the UI layer. StateFlow is a type of hot observable that emits the current and subsequent state updates to its collectors.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-Time Weather Updates with StateFlow&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Building a weather app that fetches real-time weather updates using StateFlow:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

class WeatherViewModel : ViewModel() {
    private val _weather = MutableStateFlow&amp;lt;Weather&amp;gt;(Weather.Loading)
    val weather: StateFlow&amp;lt;Weather&amp;gt; = _weather

    fun fetchWeather() {
        viewModelScope.launch {
            val newWeather = apiService.fetchWeather()
            _weather.value = newWeather
        }
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here, _weather is a MutableStateFlow that emits the current weather state. Whenever fetchWeather() is called, it updates the _weather state with the latest weather data fetched from the API, ensuring that UI components observing weather are always up-to-date.&lt;/p&gt;

&lt;p&gt;OKAY!! One more example&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F895sp4l67lxyp3gsz4si.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F895sp4l67lxyp3gsz4si.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let take an example of a &lt;strong&gt;Amazon Music:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In the** Amazon Music app**, you can use StateFlow to represent the playback state (e.g., playing, paused, stopped) and the current playing media (e.g., song, podcast).&lt;/p&gt;

&lt;p&gt;As the user interacts with the controls, the corresponding StateFlow is updated, and the UI reflects the current playback state and media information.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

class AmazonMediaPlayerRepository {
    private val _playbackState = MutableStateFlow&amp;lt;PlaybackState&amp;gt;(PlaybackState.Stopped)
    val playbackState: StateFlow&amp;lt;PlaybackState&amp;gt; = _playbackState

    private val _currentMedia = MutableStateFlow&amp;lt;Media?&amp;gt;(null)
    val currentMedia: StateFlow&amp;lt;Media?&amp;gt; = _currentMedia

    fun playMedia(media: Media) {
        // Start playing the specified media
        // Update _playbackState and _currentMedia accordingly
    }
}



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here’s how to use the above Repository.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

// Create an instance of the repository
val mediaPlayerRepository = AmazonMediaPlayerRepository()

// Start playing a media item
val media = Media(/* specify media details */)
mediaPlayerRepository.playMedia(media)

// Observe changes to the playback state
mediaPlayerRepository.playbackState.collect { state -&amp;gt;
    // Update UI or perform actions based on the playback state
}

// Observe changes to the currently playing media
mediaPlayerRepository.currentMedia.collect { media -&amp;gt;
    // Update UI or perform actions based on the currently playing media
}



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;I hope it is now clear!!!!&lt;/p&gt;




&lt;p&gt;Now lets go with the main question for the article, which one to go with and when:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffopraixh7x3qu4639g4p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffopraixh7x3qu4639g4p.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Choosing Between Compose State and StateFlow:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now that we’ve seen both &lt;strong&gt;State&lt;/strong&gt; and &lt;strong&gt;StateFlow&lt;/strong&gt; examples, let's see when to use each:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The &lt;strong&gt;State&lt;/strong&gt; can be used while managing UI-related states within a composable function. State is lightweight and perfectly suited for managing small, localized state changes that directly affect the UI.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use &lt;strong&gt;StateFlow&lt;/strong&gt; when managing state outside the UI layer, such as in ViewModels or Repositories. StateFlow provides seamless integration with coroutines and ensures that state updates are propagated efficiently across different layers of your app.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;State management&lt;/strong&gt; is a crucial aspect of building robust and reactive UIs in Jetpack Compose. Whether you’re managing UI-related state with State or handling external state with StateFlow, understanding these concepts will empower you to create delightful user experiences.&lt;/p&gt;

&lt;p&gt;So go ahead, experiment with state management in your Compose apps, and watch your UIs come to life!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6te6y0qaiaplo7sfce1s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6te6y0qaiaplo7sfce1s.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;References:&lt;/p&gt;

&lt;p&gt;Official Jetpack Compose documentation: &lt;a href="https://developer.android.com/jetpack/compose" rel="noopener noreferrer"&gt;Jetpack Compose&lt;/a&gt;&lt;br&gt;
Understanding State in Jetpack Compose: &lt;a href="https://developer.android.com/jetpack/compose/state" rel="noopener noreferrer"&gt;State in Jetpack Compose&lt;/a&gt;&lt;br&gt;
Exploring StateFlow in Kotlin: &lt;a href="https://developer.android.com/kotlin/flow/stateflow-and-sharedflow" rel="noopener noreferrer"&gt;StateFlow Explained&lt;/a&gt;&lt;/p&gt;




</description>
    </item>
    <item>
      <title>Unraveling the Magic of Loopers and Executors in Android</title>
      <dc:creator>Rishabh Gupta</dc:creator>
      <pubDate>Mon, 18 Mar 2024 19:38:18 +0000</pubDate>
      <link>https://dev.to/rishabhtech94/unraveling-the-magic-of-loopers-and-executors-in-android-2g6c</link>
      <guid>https://dev.to/rishabhtech94/unraveling-the-magic-of-loopers-and-executors-in-android-2g6c</guid>
      <description>&lt;p&gt;&lt;strong&gt;In the bustling world of Android development,&lt;/strong&gt; two mystical beings play a crucial role in ensuring smooth operation: &lt;strong&gt;Loopers and Executors.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;These components form the backbone of asynchronous processing, allowing your app to juggle multiple tasks without skipping a beat.&lt;/p&gt;

&lt;p&gt;Imagine them as diligent workers behind the scenes, orchestrating tasks seamlessly to keep your app running efficiently.&lt;/p&gt;

&lt;p&gt;In this Chapter of Learning Android, Lets us start from the basic story.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgl0xonl2h9axxj7q8cq5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgl0xonl2h9axxj7q8cq5.png" alt="Image description" width="800" height="390"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Let meet our first character The Loopers:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In our story, the Looper is like a dedicated messenger who tirelessly shuttles between different parts of your app, ensuring that tasks are executed in the right order and at the right time.&lt;/p&gt;

&lt;p&gt;Every Android app operates within a main thread, which is like a busy highway where all the crucial tasks, such as updating the UI or handling user interactions, take place. Now, if a time-consuming task is thrown onto this highway, it can cause a traffic jam, resulting in a sluggish user experience or even freezing the app altogether.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx8bnc08r03pambou43bx.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx8bnc08r03pambou43bx.gif" alt="Image description" width="498" height="373"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Yes you are correct, this is what is mean to say !!!!!!!!!!!!!&lt;/p&gt;

&lt;p&gt;So This is where the Looper swoops in to save the day.&lt;/p&gt;

&lt;p&gt;It creates a special loop within the main thread, called “Looper thread,” where it handles tasks efficiently, one after the other, without causing any gridlock. Imagine the Looper as a skilled traffic controller, ensuring that each task moves smoothly through the thread, preventing congestion and keeping your app responsive.&lt;/p&gt;

&lt;p&gt;Enter the Executors:&lt;/p&gt;

&lt;p&gt;But what happens when our trusty Looper has too many tasks on its plate? This is where Executors step into the spotlight. Think of them as resourceful assistants who help the Looper manage its workload effectively.&lt;/p&gt;

&lt;p&gt;Executors work behind the scenes to delegate tasks to separate worker threads, allowing heavy lifting to be performed without burdening the main thread.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo5owqzq9h0lv05iwgbft.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo5owqzq9h0lv05iwgbft.jpg" alt="Image description" width="800" height="533"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;By offloading tasks to Executors, the Looper can focus on handling essential operations within the main thread, ensuring that your app remains snappy and responsive. It’s like having a well-oiled machine where each component plays its part seamlessly, resulting in a flawless user experience.&lt;/p&gt;

&lt;p&gt;Example Time&lt;/p&gt;

&lt;p&gt;Imagine you’re developing a weather app that needs to fetch live updates from the internet while simultaneously updating the UI with the latest data. Without Loopers and Executors, this could lead to a clunky user experience, with the UI freezing every time the app fetches new information.&lt;/p&gt;

&lt;p&gt;However, by employing Loopers to manage tasks within the main thread and Executors to handle network requests and data processing in the background, your app can deliver a smooth and uninterrupted experience. It’s like having a team of dedicated workers ensuring that your app runs like a well-oiled machine, regardless of the complexity of the tasks at hand.&lt;/p&gt;

&lt;p&gt;Loopers and Executors are indispensable allies, working tirelessly behind the scenes to ensure optimal performance and a seamless user experience. Whether it’s managing tasks within the main thread or delegating heavy lifting to background threads, these mystical beings play a vital role in the success of your app.&lt;/p&gt;

&lt;p&gt;So, the next time you appreciate the seamless functioning of your favorite Android app, remember to acknowledge the unsung heroes behind it — the Loopers and Executors who make it all happen. Their work is essential in ensuring a smooth user experience.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxzp3knf9t7w23dkhzywm.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxzp3knf9t7w23dkhzywm.jpeg" alt="Image description" width="300" height="168"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here is a small snippet!!!!!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import android.os.Handler
import android.os.Looper
import java.util.concurrent.Executors

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //Using Executors
        val executor = Executors.newSingleThreadExecutor()

        executor.execute {
            // Executed on a separate background threadfor executing tasks asynchronously.
            println("Task executed on background thread.")

            // Simulating heavy task
            Thread.sleep(2000)

            // Update UI on the main thread using a Handler
            Handler(Looper.getMainLooper()).post {
                // UI update code here
                println("Updating UI on the main thread after task completion.")
            }
        }

        Using Loopers
        val handlerThread = HandlerThread("HandlerThread")
        handlerThread.start()

        val looper = handlerThread.looper
        val handler = Handler(looper)

        handler.post {
            // Executed on the background thread associated with the Looper
            println("Task executed on background thread with Looper.")

            // Simulating some heavy task
            Thread.sleep(2000)

            // Update UI on the main thread using a Handler
            Handler(Looper.getMainLooper()).post {
                // UI update code here
                println("Updating UI on the main thread after task completion with Looper.")
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;We have created a HandlerThread named "HandlerThread", which internally creates a new background thread with its own Looper.&lt;/li&gt;
&lt;li&gt;We post a task to the handler using handler.post { ... }, similar to the executor example. The task is executed on the background thread associated with the Looper. After the task completes, Handler post an update to the UI thread.&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>android</category>
      <category>androiddev</category>
      <category>mobile</category>
      <category>mobileapplication</category>
    </item>
  </channel>
</rss>
