<?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 Shashi Shekhar Mishra on Medium]]></title>
        <description><![CDATA[Stories by Shashi Shekhar Mishra on Medium]]></description>
        <link>https://medium.com/@shashishekhar93?source=rss-4b706ed94a09------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0hgfuFi6a92shftV1dgrtg.jpeg</url>
            <title>Stories by Shashi Shekhar Mishra on Medium</title>
            <link>https://medium.com/@shashishekhar93?source=rss-4b706ed94a09------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 00:41:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shashishekhar93/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[Why repeating the same navigation logic is like wasting water  (Android Dev Lesson)]]></title>
            <link>https://blog.stackademic.com/why-repeating-the-same-navigation-logic-is-like-wasting-water-android-dev-lesson-0cc94dfa89d5?source=rss-4b706ed94a09------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cc94dfa89d5</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Shashi Shekhar Mishra]]></dc:creator>
            <pubDate>Fri, 03 Apr 2026 06:21:09 GMT</pubDate>
            <atom:updated>2026-04-07T09:03:55.673Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PMAiWAe9sEMTXV9BLgjiyQ.png" /></figure><p>Last week, I came across a simple but powerful idea while reading about water conservation:</p><blockquote>“If every house builds its own pipeline for the same water source, you waste resources. A centralised system is always more efficient.”</blockquote><p>That immediately reminded me of something we often do in Android apps.</p><h3>🌍 The Problem (Relatable Even for Non-Developers)</h3><p>Imagine an app with multiple screens:</p><ul><li>Home</li><li>Assignments</li><li>Attendance</li><li>Doubts</li><li>Profile</li></ul><p>And every screen has a notification icon 🔔</p><p>Now, whenever the user taps it, they should go to: Notifications screen</p><h3>The Common Mistake</h3><p>Most developers do this:</p><ul><li>Add navigation logic in every fragment</li><li>Create separate navigation actions in XML</li><li>Duplicate the same click listener everywhere</li></ul><p>This works… but it’s inefficient.</p><p>Just like building 5 separate water pipelines for the same tap</p><h3>💡 The Better Approach (Centralised Navigation)</h3><p>Instead of repeating logic, we can:</p><ul><li>Define a global navigation action</li><li>Create a centralised function</li><li>Reuse it across all fragments</li></ul><h3>Step 1: Define a Global Action (NavGraph)</h3><pre>&lt;!-- app_nav_graph.xml --&gt;<br>&lt;navigation ...&gt;<br>&lt;!-- Global Action --&gt;<br>    &lt;action<br>        android:id=&quot;@+id/action_global_navigation_notification&quot;<br>        app:destination=&quot;@id/navigation_notification&quot;<br>        app:enterAnim=&quot;@anim/nav_default_enter_anim&quot;<br>        app:exitAnim=&quot;@anim/nav_default_exit_anim&quot; /&gt;<br>    &lt;fragment<br>        android:id=&quot;@+id/navigation_home&quot;<br>        ... /&gt;<br>    &lt;fragment<br>        android:id=&quot;@+id/navigation_notification&quot;<br>        android:name=&quot;com.yourapp.NotificationsFragment&quot;<br>        ... /&gt;<br>&lt;/navigation&gt;</pre><p>👉 This makes the notification destination accessible from any fragment</p><h3>Step 2: Create a Centralised Extension Function</h3><pre>fun View.setupNotificationClick() {<br>    setOnClickListener {<br>        val navController = findNavController()<br>        // Prevent duplicate navigation crashes<br>        val currentDestination = navController.currentDestination?.id<br>        if (currentDestination != R.id.navigation_notification) {<br>            navController.navigate(R.id.action_global_navigation_notification)<br>        }<br>    }<br>}</pre><h3>Step 3: Use It Anywhere (Clean &amp; Simple)</h3><pre>binding.ivNotification.setupNotificationClick()</pre><p>That’s it.</p><p>No repetition. No clutter.</p><h3>Why This is the Best Practice?</h3><h3>✅ DRY Principle (Don’t Repeat Yourself)</h3><p>Change logic in one place → works everywhere</p><h3>✅ Cleaner NavGraph</h3><p>No need to draw multiple arrows for every fragment</p><h3>✅ Safer Navigation</h3><p>Prevents duplicate navigation crashes</p><h3>✅ Scalable Codebase</h3><p>Adding new screens? No extra work needed</p><h3>Final Thought</h3><p>Good engineering is not about writing more code. It’s about writing less, but smarter code.</p><p>Just like nature:</p><blockquote><em>Take only what you need, and build systems that scale.</em></blockquote><p>Have you ever refactored something simple… and realized how much cleaner your code became?</p><p>#AndroidDevelopment #Kotlin #JetpackNavigation #MobileDevelopment #CleanCode #SoftwareEngineering</p><p><strong>A message from our Founder</strong></p><p>Hey, <a href="https://linkedin.com/in/sunilsandhu">Sunil</a> here. I wanted to take a moment to thank you for reading until the end and for being a part of this community. Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? We don’t receive any funding, we do this to support the community.</p><p>If you want to show some love, please take a moment to follow me on <a href="https://linkedin.com/in/sunilsandhu">LinkedIn</a>, <a href="https://tiktok.com/@messyfounder">TikTok</a>, <a href="https://instagram.com/sunilsandhu">Instagram</a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/">weekly newsletter</a>. And before you go, don’t forget to clap and follow the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cc94dfa89d5" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/why-repeating-the-same-navigation-logic-is-like-wasting-water-android-dev-lesson-0cc94dfa89d5">Why repeating the same navigation logic is like wasting water 💧 (Android Dev Lesson)</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scrolling endlessly… but ever wondered how apps don’t load everything at once?]]></title>
            <link>https://blog.stackademic.com/scrolling-endlessly-but-ever-wondered-how-apps-dont-load-everything-at-once-0bc63875c7ed?source=rss-4b706ed94a09------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bc63875c7ed</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Shashi Shekhar Mishra]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 04:46:54 GMT</pubDate>
            <atom:updated>2026-04-01T06:03:04.313Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*AXhmh1MkYCbpxDDVCyKRdA.png" /></figure><p>Last weekend, I was watching a documentary on water conservation.</p><p>One line stuck with me:</p><blockquote>“You don’t drain the entire lake to drink water. You take only what you need, when you need it.</blockquote><p>That’s exactly how modern apps handle large data.</p><h3>The Problem</h3><p>Imagine loading:</p><ul><li>10,000 products</li><li>50,000 driver records</li><li>Infinite social media posts</li></ul><p>If an app loads everything at once:</p><ul><li>App becomes slow</li><li>Memory usage spikes</li><li>Bad user experience</li></ul><h3>The Idea (Simple Explanation)</h3><p>Instead of loading everything:</p><p>Load data in small chunks (pages) , Fetch more only when user scrolls</p><p>Just like:Taking water bucket by bucket, not the whole lake</p><h3>Android Solution: Paging 3 + PagingSource</h3><p>In Android, this is handled using Paging 3 library</p><p>At the core of it is:</p><p>PagingSource</p><p>It decides:</p><ul><li>What data to load.</li><li>From where to load.</li><li>What to load next.</li></ul><h3>How PagingSource Thinks</h3><p>It works like this:</p><ol><li>Load first page</li><li>User scrolls</li><li>Load next page</li><li>Repeat…</li></ol><h3>Code Example (Real Implementation)</h3><h3>PagingSource</h3><pre>class UserPagingSource(<br>    private val api: ApiService<br>) : PagingSource&lt;Int, User&gt;() {<br>override suspend fun load(params: LoadParams&lt;Int&gt;): LoadResult&lt;Int, User&gt; {<br>        return try {<br>            val page = params.key ?: 1<br>            val response = api.getUsers(page)<br>            LoadResult.Page(<br>                data = response.users,<br>                prevKey = if (page == 1) null else page - 1,<br>                nextKey = if (response.users.isEmpty()) null else page + 1<br>            )<br>        } catch (e: Exception) {<br>            LoadResult.Error(e)<br>        }<br>    }<br>    override fun getRefreshKey(state: PagingState&lt;Int, User&gt;): Int? {<br>        return state.anchorPosition?.let { position -&gt;<br>            state.closestPageToPosition(position)?.prevKey?.plus(1)<br>                ?: state.closestPageToPosition(position)?.nextKey?.minus(1)<br>        }<br>    }<br>}</pre><h3>ViewModel</h3><pre>val usersFlow = Pager(<br>    config = PagingConfig(pageSize = 20),<br>    pagingSourceFactory = { UserPagingSource(api) }<br>).flow.cachedIn(viewModelScope)</pre><h3>RecyclerView Adapter</h3><pre>lifecycleScope.launch {<br>    viewModel.usersFlow.collectLatest { pagingData -&gt;<br>        adapter.submitData(pagingData)<br>    }<br>}</pre><h3>Why This Matters</h3><ol><li>Smooth scrolling.</li><li>Better performance.</li><li>Reduced memory usage.</li><li>Scalable apps.</li></ol><h3>Final Thought</h3><p>Good engineering is not about loading more. It’s about loading just enough, at the right time.</p><p>Just like nature teaches us.</p><p>Have you implemented Paging 3 in your apps? Or still using manual pagination?</p><p>#AndroidDevelopment #Kotlin #Paging3 #MobileDevelopment #SoftwareEngineering #AppDevelopment</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bc63875c7ed" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/scrolling-endlessly-but-ever-wondered-how-apps-dont-load-everything-at-once-0bc63875c7ed">Scrolling endlessly… but ever wondered how apps don’t load everything at once?</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Inversion Principle (DIP) - Explained with Dagger 2.]]></title>
            <link>https://blog.stackademic.com/dependency-inversion-principle-dip-explained-with-dagger-2-327eed051ec0?source=rss-4b706ed94a09------2</link>
            <guid isPermaLink="false">https://medium.com/p/327eed051ec0</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Shashi Shekhar Mishra]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 08:51:56 GMT</pubDate>
            <atom:updated>2025-11-13T05:16:52.756Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTyLzMTfZy7ObDqZMkuWHQ.png" /></figure><p>When your ViewModel directly depends on Retrofit or Room, changing a data source becomes a headache.<br> That’s where the <strong>Dependency Inversion Principle (‘D’ of SOLID Principles) </strong>saves the day — make your high-level code depend on <strong>interfaces</strong>, not <strong>concrete classes</strong>.</p><p>Here’s how Dagger 2 injects the right implementation while keeping everything clean 👇</p><h3>Concept:-</h3><blockquote><em>High-level classes (like your </em><em>ViewModel) should depend on </em><strong><em>abstractions</em></strong><em>, not </em><strong><em>concrete implementations</em></strong><em>.</em></blockquote><h3>Without DIP — Tight Coupling</h3><pre>class UserViewModel : ViewModel() {<br>    private val apiService = ApiService()  // Direct dependency</pre><pre>    fun getUser(): User {<br>        return apiService.fetchUser()<br>    }<br>}</pre><p>Here the ViewModel depends <strong>directly</strong> on ApiService.<br> If you replace ApiService with a different data source (say Firebase or Room), you must <strong>modify</strong> UserViewModel → violating DIP.</p><h3>With DIP + Dagger 2 — Loose Coupling</h3><p>We introduce an <strong>interface (abstraction)</strong> and let Dagger provide the implementation.</p><h4>Step 1️⃣ — Create the abstraction</h4><pre>interface UserRepository {<br>    fun getUser(): User<br>}</pre><h4>Step 2️⃣ — Implement the abstraction</h4><pre>class RemoteUserRepository @Inject constructor(<br>    private val api: ApiService<br>) : UserRepository {<br>    override fun getUser(): User = api.fetchUser()<br>}</pre><h4>Step 3️⃣ — Bind the implementation to the interface</h4><pre>@Module<br>interface RepositoryModule {<br>    @Binds<br>    fun bindUserRepository(<br>        impl: RemoteUserRepository<br>    ): UserRepository<br>}</pre><h4>Step 4️⃣ — Inject abstraction into ViewModel</h4><pre>class UserViewModel @Inject constructor(<br>    private val repository: UserRepository<br>) : ViewModel() {</pre><pre>    fun getUser(): User = repository.getUser()<br>}</pre><h4>Step 5️⃣ — Provide dependencies with a Dagger component</h4><pre>@Component(modules = [RepositoryModule::class])<br>interface AppComponent {<br>    fun inject(activity: MainActivity)<br>}</pre><h4>Step 6️⃣ — Use it in your Activity</h4><pre>class MainActivity : AppCompatActivity() {<br>    @Inject lateinit var viewModel: UserViewModel</pre><pre>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        DaggerAppComponent.create().inject(this)</pre><pre>        val user = viewModel.getUser()<br>        println(&quot;User: $user&quot;)<br>    }<br>}</pre><h3>Result</h3><ul><li>UserViewModel no longer depends on any concrete data source.</li><li>You can easily swap RemoteUserRepository with LocalUserRepository or FakeUserRepository (for testing) without touching ViewModel code.</li><li>This keeps your code <strong>flexible</strong>, <strong>testable</strong>, and <strong>maintainable</strong>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=327eed051ec0" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/dependency-inversion-principle-dip-explained-with-dagger-2-327eed051ec0">Dependency Inversion Principle (DIP) - Explained with Dagger 2.</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“UI State in Jetpack Compose: Understanding LiveData, mutableStateOf, and StateFlow”]]></title>
            <link>https://medium.com/@shashishekhar93/ui-state-in-jetpack-compose-understanding-livedata-mutablestateof-and-stateflow-f1849ed4bf6f?source=rss-4b706ed94a09------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1849ed4bf6f</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Shashi Shekhar Mishra]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 05:11:30 GMT</pubDate>
            <atom:updated>2025-08-28T05:11:30.764Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“Life is all about <strong>change and response</strong>.<br> When a baby cries, the mother responds.<br> When the seasons shift, nature adapts.<br> When our emotions fluctuate, our friends notice.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kae10HOsEPf-UPwsiisg_g.png" /></figure><p>In Android development too, our <strong>UI is alive</strong> — it must observe changes in data and respond instantly. Just as we cannot freeze life into one static moment, we cannot freeze apps into a single UI state. That’s where tools like <strong>LiveData, mutableStateOf, and StateFlow</strong> step in — each one helping us handle change, but with different styles and philosophies.</p><p>Let’s understand these terms in First Come First Serve Basis.<br>1.<strong>Live Data 👈</strong><br>2.mutableStateOf<br>3.StateFlow</p><p><strong>LiveData:-<br>Before Jetpack Compose and Flow introduced</strong>,<br><strong>LiveData</strong> was the solution for handling reactive UI state in Android.<br>It is a <strong>lifecycle-aware observable data holder class.</strong> <br>It automatically observes the <strong>lifecycle of UI components</strong> (Activity, Fragment).<br><strong>Introduced</strong> in <strong>2017</strong> as part of <strong>Android Architecture Components (AAC)</strong>.<br><strong>Purpose</strong>: To create <strong>lifecycle-aware observable data holders</strong> for Activities/Fragments.<br>Commonly used with <strong>XML-based UI</strong> + findViewById.<br>Pattern: <strong>MVVM (Model-View-ViewModel)</strong> → ViewModel holds LiveData, Activity/Fragment observes it.</p><p><strong>Dependency for LiveData:-</strong><br>implementation &quot;androidx.lifecycle:lifecycle-livedata-ktx:2.8.4&quot;</p><p>Let’s understand with example:-<br>In below code, I have created a View Model class.<br>This class extends <strong>ViewModel</strong>, which means it is <strong>lifecycle-aware</strong> and survives configuration changes (like screen rotation).<br>Any data stored here will <strong>not reset</strong> when the screen rotates.</p><pre>class Module7ViewModel : ViewModel() {<br><br>    private val _message = MutableLiveData&lt;String&gt;(&quot;This is default message&quot;)<br><br>    val message: LiveData&lt;String&gt; get() = _message<br><br>    fun updateMessage(newMessage: String) {<br>        _message.value = newMessage<br>    }<br>}</pre><p>_message is a <strong>MutableLiveData</strong> object that holds a String.<br>MutableLiveData means we can <strong>change/update</strong> the value inside it.<br>Initially, it has the value &quot;This is default message&quot;.</p><p>val message: LiveData&lt;String&gt; get() = _message<br> Here, we are exposing mutable <strong>_message</strong> in to a read-only LiveData object i.e. <strong>message</strong> to make it readable by other classes(Activities/Fragments).<br><strong>This Practice is called Encapsulation.</strong></p><p>UpdateMessage() updates the <strong>_message</strong> value.<br>So, whenever _message.value changes → all observers (UI components) automatically get the updated value.</p><p>Now let’s move to our main activity class and update this value on button click.</p><pre>class LiveDataPracticeActivity : ComponentActivity() {<br>    lateinit var viewModel: LiveDataViewModel<br>    val textviewMessage: TextView by lazy { findViewById&lt;TextView&gt;(R.id.textview_message) }<br>    val updateMessage : Button by lazy { findViewById&lt;Button&gt;(R.id.updateMessage) }<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        viewModel = ViewModelProvider(this).get(LiveDataViewModel::class.java)<br>        setContentView(R.layout.activity_live_data_main)<br>        viewModel.message.observe(this,{<br>            textviewMessage.text = it<br>        })<br><br>        updateMessage.setOnClickListener {<br>            viewModel.updateMessage(&quot;this is updated Message&quot;)<br>        }<br><br>    }<br>}</pre><p>by lazy <strong>initialises the view only when used</strong> for the first time → improves performance.<br>ViewModelProvider(this) attaches the ViewModel to this Activity’s lifecycle.<br>Here <strong>this</strong> is current activity scope.<br>By using this, Even if the screen rotates, the data inside ViewModel <strong>does not reset</strong>.</p><p>Lastly , don’t forget to add the activity in Manifest.xml file.</p><pre>&lt;activity android:name=&quot;.LiveDataPracticeActivity&quot;<br>            android:exported=&quot;true&quot;&gt;<br>            &lt;intent-filter&gt;<br>                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;<br><br>                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;<br>            &lt;/intent-filter&gt;<br>        &lt;/activity&gt;</pre><p>Try these codes in your Android Studio and see the results. In the second part of this 3 part series, I’ll cover the <strong>mutableStateOf.</strong></p><p>Stay tuned for more😀…<br><a href="http://www.linkedin.com/in/shashi-shekhar-mishra-150565bb">LinkedIn</a>, <a href="https://medium.com/@shekhar_mishra">Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1849ed4bf6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From App to APK :- How to make List in Android Jetpack Compose?]]></title>
            <link>https://medium.com/@shashishekhar93/from-app-to-apk-how-to-make-list-in-android-jetpack-compose-d6bc7b0e6a13?source=rss-4b706ed94a09------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6bc7b0e6a13</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Shashi Shekhar Mishra]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 11:16:33 GMT</pubDate>
            <atom:updated>2025-08-25T11:16:33.907Z</atom:updated>
            <content:encoded><![CDATA[<h3>From App to APK :- How to make List in Android Jetpack Compose?</h3><p><strong>“Complexity is just chaos without proper organisation.”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VRXPZMg8C0tEckGhOP2Igg.png" /></figure><p>When you walk into an <strong>equatorial rainforest</strong>, it feels <strong>endless</strong>. Thousands of <strong>trees</strong>, countless <strong>leaves</strong>, infinite <strong>life forms</strong> — yet everything has its own place and purpose. The forest doesn’t collapse under its complexity; instead, it thrives because it’s beautifully organised.</p><p>Similarly, apps often face streams of endless data — contacts, messages, products — without structure, it’s like wandering a jungle without a path. Jetpack Compose lists transform <strong>raw data</strong> into clear, scrollable, elegant trails.</p><p><strong>This article</strong> shows how to build an interactive <strong>recipe list</strong> with expandable cards for a sleek, user-friendly UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pcEs3F9Uula6IlLnw23WnQ.png" /></figure><p>So let’s start building our very first list app. For that, <br>let’s make a model class for our List first…</p><h3>Data Model: Recipe</h3><pre>data class Recipe(<br>    val meal: String,<br>    val category: String,<br>    val area: String,<br>    val thumbImage: String<br>)</pre><p>The core data is modelled in a Recipe Kotlin data class. This represents each recipe with essential fields:<br>meal: Name of recipe.<br>category: Recipe category (Dessert, Chicken, etc.<br>area: Origin or cuisine area.<br>thumbImage: URL of the recipe thumbnail image.</p><p>The app uses a predefined list called demoRecipeList which contains multiple Recipe instances for testing purposes.</p><pre>val demoRecipeList = listOf(<br>    Recipe(<br>        meal = &quot;Apple Frangipan Tart&quot;,<br>        category = &quot;Dessert&quot;,<br>        area = &quot;British&quot;,<br>        instructions = &quot;Preheat the oven to 200C/180C Fan/Gas 6. Put the biscuits in a large re-sealable freezer bag and bash with a rolling pin into fine crumbs. Melt the butter in a small pan, then add the biscuit crumbs and stir until coated with butter. Tip into the tart tin and, using the back of a spoon, press over the base and sides of the tin to give an even layer. Chill in the fridge while you make the filling. Cream together the butter and sugar until light and fluffy. Mix in the eggs, then add ground almonds and almond extract. Peel and slice apples, arrange over biscuit base, spread frangipane filling, level surface, sprinkle flaked almonds, bake 20-25 minutes until golden, cool 15 minutes, serve warm with cream, crème fraiche or ice cream.&quot;,<br>        thumbImage = &quot;https://www.themealdb.com/images/media/meals/wxywrq1468235067.jpg&quot;<br>    ),...<br>)</pre><p>For now, I have added only one instance. It is highly recommended to add atleast 5–6 more Items using , followed by Recipe() instance filled with (meal = &quot; &quot;, category = &quot; &quot;,..,..,.. etc) .</p><h3>Main Screen Setup with Scaffold and TopAppBar</h3><p>The main activity uses Compose’s Scaffold to create a basic app UI scaffold with a top app bar for screen title.<br>Here,<br>CenterAlignedTopAppBar: Displays title &quot;Fruit List&quot; center-aligned with custom colours.<br>Box fills the screen area to hold the recipe list content.See Below code</p><pre>override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br>    setContent {<br>        RecipeListTheme {<br>            Scaffold(<br>                topBar = {<br>                    CenterAlignedTopAppBar(<br>                        title = { Text(&quot;Fruit List&quot;) },<br>                        colors = TopAppBarDefaults.centerAlignedTopAppBarColors(<br>                            containerColor = colorResource(id = R.color.purple_200),<br>                            titleContentColor = colorResource(id = R.color.white)<br>                        )<br>                    )<br>                }<br>            ) { innerPadding -&gt;<br>                Box(<br>                    modifier = Modifier<br>                        .padding(innerPadding)<br>                        .fillMaxSize(),<br>                    contentAlignment = Alignment.Center<br>                ) {<br>                    RecipeItem(demoRecipeList)  // Pass the recipe list here<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><strong>Scaffold</strong> is like a <strong>ready-made layout template</strong> that holds common app UI parts such as the <strong>top bar</strong>, <strong>bottom bar</strong>, <strong>floating action button</strong>, and main content. It <strong>automatically</strong> <strong>arranges</strong> these elements in the right places, so you don’t have to manage their positioning manually.</p><h3>Displaying the List: LazyColumn with Recipe Items</h3><p>For efficient display of large lists, LazyColumn is used, which composes only the visible items on screen. The RecipeItem composable takes a list of recipes and displays each one using an expandable card UI like this —</p><pre>@Composable<br>fun RecipeItem(recipeList: List&lt;Recipe&gt;) {<br>    LazyColumn {<br>        items(recipeList) { recipe -&gt;<br>            ExpandableRecipeItem(recipe)<br>        }<br>    }<br>}</pre><h3>Expandable Recipe Card with Animation</h3><p>Each recipe is shown as a card which <strong>expands/collapses</strong> to reveal or hide detailed cooking instructions when clicked. This improves usability by keeping the UI clean while allowing users to explore details on demand.</p><p>Key parts of the expandable card:<br>Uses Card with rounded corners and elevation for material styling<br>Tappable (clickable) to toggle expansion state<br>Uses AnimatedVisibility with vertical expand/shrink animation for smooth transitions<br>Displays image, meal name, category &amp; area, and conditionally instructions.</p><pre>@Composable<br>fun ExpandableRecipeItem(recipe: Recipe) {<br>    var expanded by remember { mutableStateOf(false) }<br><br>    Card(<br>        shape = RoundedCornerShape(8.dp),<br>        elevation = CardDefaults.cardElevation(4.dp),<br>        modifier = Modifier<br>            .padding(8.dp)<br>            .fillMaxWidth()<br>            .clickable { expanded = !expanded }<br>    ) {<br>        Column(modifier = Modifier.padding(16.dp)) {<br>            Image(<br>                painter = rememberAsyncImagePainter(recipe.thumbImage),<br>                contentDescription = recipe.meal,<br>                modifier = Modifier<br>                    .height(180.dp)<br>                    .fillMaxWidth()<br>                    .clip(RoundedCornerShape(8.dp)),<br>                contentScale = ContentScale.Crop<br>            )<br><br>            Spacer(modifier = Modifier.height(12.dp))<br><br>            Text(<br>                text = recipe.meal,<br>                style = MaterialTheme.typography.titleMedium,<br>                fontWeight = FontWeight.Bold<br>            )<br><br>            Text(<br>                text = &quot;${recipe.category} | ${recipe.area}&quot;,<br>                style = MaterialTheme.typography.labelMedium,<br>                modifier = Modifier.padding(vertical = 4.dp)<br>            )<br><br>            AnimatedVisibility(<br>                visible = expanded,<br>                enter = expandVertically(animationSpec = tween(300)),<br>                exit = shrinkVertically(animationSpec = tween(300))<br>            ) {<br>                Text(<br>                    text = recipe.instructions,<br>                    style = MaterialTheme.typography.bodyMedium,<br>                    modifier = Modifier.padding(top = 6.dp)<br>                )<br>            }<br>        }<br>    }<br>}</pre><p>We need to know what is the importance of remember { mutableStateOf() } here in above code snippet.</p><p>remember { mutableStateOf() } in <strong>Jetpack Compose</strong> is a way to <strong>store a piece of data (state)</strong> that can <strong>change and survive recompositions</strong> of a composable function. It <strong>remembers the value across UI updates</strong> so the data <strong>doesn&#39;t reset</strong> every time the UI redraws.</p><p>remember keeps the value in memory as long as the composable is kept in the UI.<br>mutableStateOf creates a state holder that notifies Compose when the value changes, triggering UI to recompose to reflect changes.<br>Other use-cases are:- Toggle button or any UI visibility.</p><p>The final App will look like this —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hO6U1EqdqW6JXVMQK2mBAg.jpeg" /></figure><p>By combining a well-defined data model, Jetpack Compose’s modern UI components, and animation APIs, the app achieves an elegant recipe list with expandable details. This approach results in a user-friendly, maintainable, and aesthetically pleasing Android app adaptable to various listing and detail scenarios.</p><p>Stay tuned for more😀…<br><a href="http://www.linkedin.com/in/shashi-shekhar-mishra-150565bb">LinkedIn</a>, <a href="https://medium.com/@shekhar_mishra">Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6bc7b0e6a13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From App to APK: What is a Coroutine? what it’s Used?]]></title>
            <link>https://medium.com/@shashishekhar93/from-app-to-apk-what-is-a-coroutine-what-its-used-18e978ceb712?source=rss-4b706ed94a09------2</link>
            <guid isPermaLink="false">https://medium.com/p/18e978ceb712</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Shashi Shekhar Mishra]]></dc:creator>
            <pubDate>Thu, 21 Aug 2025 05:23:06 GMT</pubDate>
            <atom:updated>2025-08-21T05:23:06.078Z</atom:updated>
            <content:encoded><![CDATA[<p>“<strong>Coroutines are to Android what balance is to the rainforest — silent, powerful, and absolutely essential for survival.”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SxGn3bvym4dfWjquLXYFFA.png" /></figure><p>Imagine you’re standing in the heart of an <strong>equatorial rainforest</strong>.<br>Deep in where, life never stops moving. A parrot takes flight, a jaguar prowls, rain patters on the leaves — all happening at once, yet nothing collides. There’s harmony in the chaos.</p><p>Now imagine your Android app. Network calls, database operations, UI updates — all trying to happen together. Without balance, everything freezes.</p><p>This is where <strong>Kotlin Coroutines</strong> step in. Like the hidden <strong>rhythm</strong> of the forest, they quietly coordinate tasks, ensuring your app runs <strong>smoothly</strong> — fast on the surface, powerful underneath.</p><h3>What are Coroutines?</h3><p>Lightweight threads for <strong>asynchronous programming</strong>.<br>They help write <strong>sequential-looking code</strong> for async tasks (network calls, DB queries).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*yiKJC3aWC_yWxxKVKs89aQ.png" /><figcaption>example of a coroutine.</figcaption></figure><ul><li>runBlocking { ... } → Creates a <strong>coroutine scope</strong> and runs code inside it.<br>launch { ... } → Starts a <strong>new coroutine</strong> that runs <em>concurrently</em>.<br>delay(1000L) → Suspends the coroutine without blocking the thread.</li></ul><pre>Output:<br>Hello,<br>world!</pre><p><strong>Basics of Coroutines:-</strong><br>Coroutine is a vast concept. For now, let’s learn about some basics.<br>A coroutine is a combination of several components as:<br>1. Coroutine Builders.<br>2. Coroutine Scope.<br>3. Dispatchers.<br>4. Coroutine Concurrency.</p><p><strong>Coroutine Builders:-<br></strong>As we can see in the example, <strong>runBlocking</strong> {...} and <strong>launch</strong>{...} are being used.These are coroutine builders.<br>A <strong>coroutine builder</strong> is a function that helps you <strong>start a new coroutine</strong>.<br> It defines <strong>how</strong> and <strong>where</strong> the coroutine will run (its scope, context, and behavior).</p><p>The most commonly used coroutine builders are:<br><strong>launch { ... }</strong> → Starts a coroutine that runs in the background and doesn’t return a result.<br><strong>async { ... }</strong> → Starts a coroutine that can return a result via await().<br>lelt’s so an example.</p><pre>fun main() {<br>    runBlocking {<br>        useAsyncFunctionNormally()<br>    }<br>}<br>suspend fun CoroutineScope.useAsyncFunctionNormally() {<br>    measureTimeMillis {<br>        val resultOne = async { value_one() }<br>        val resultTwo = async { value_two() }<br>        val finalResult = resultOne.await() + resultTwo.await()<br>        println(&quot;Final Result: $finalResult&quot;)<br>    }<br>        .also { time -&gt;<br>            println(&quot;Time taken: $time ms&quot;)<br>        }<br>}<br><br>Output:<br>Final Result: 20</pre><p><strong>runBlocking { ... }</strong> → Starts a coroutine and blocks the current thread until it completes (useful in main() or tests).<br>We can see that Coroutine Scope is defined here. Let’s talk about it.</p><p><strong>Coroutine Scope:- <br></strong>Every coroutine in Kotlin needs a <strong>scope</strong>.<br> Think of a <strong>CoroutineScope</strong> as a <em>container</em> that keeps track of all the coroutines you launch inside it.<br><strong>You can create a scope in two main ways:</strong><br><strong>a.</strong> Using CoroutineScope() constructor. Let’s see an example.</p><pre>fun main() = runBlocking {<br>    // Create a custom scope with Dispatchers.Default<br>    val scope = CoroutineScope(Dispatchers.Default)<br>    // Launch a coroutine inside the scope<br>    val job = scope.launch {<br>        repeat(3) { i -&gt;<br>            println(&quot;Coroutine running: $i on ${Thread.currentThread().name}&quot;)<br>            delay(500)<br>        }<br>    }<br>    println(&quot;Main program is running...&quot;)<br>    // Wait for coroutine to finish<br>    job.join()<br>    println(&quot;Main program ends.&quot;)<br>}<br>output:<br>Main program is running...<br>Coroutine running: 0 on DefaultDispatcher-worker-1<br>Coroutine running: 1 on DefaultDispatcher-worker-1<br>Coroutine running: 2 on DefaultDispatcher-worker-1<br>Main program ends.</pre><p><strong>scope.launch{...} </strong>returns a job() object. This object’s function <strong>job.join() </strong>ensures the main program waits until the coroutine completes.<br>Coroutines can be cancelled using <strong>job.cancel() object</strong>.</p><p><strong>b. Using predefined scopes (Best Practice in Android)<br></strong>lifecycleScope → attached to Activity / Fragment lifecycle. And destroyed when Activity class’s <strong>onDestroy()</strong> called.</p><pre>class MainActivity : AppCompatActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br>        // Launch a coroutine tied to Activity lifecycle<br>        lifecycleScope.launch {<br>            repeat(3) { i -&gt;<br>                delay(1000) // imitate work<br>                println(&quot;Coroutine running $i in lifecycleScope&quot;)<br>            }<br>        }<br>        println(&quot;Main thread is free to do other work...&quot;)<br>    }<br>}<br>output:<br>Main thread is free to do other work...<br>Coroutine running 0 in lifecycleScope<br>Coroutine running 1 in lifecycleScope<br>Coroutine running 2 in lifecycleScope</pre><p>viewModelScope → Tied to ViewModel lifecycle.<br>We will learn about practical uses of viewModelScope in our upcoming articles.</p><pre>class MyViewModel : ViewModel() {<br>    private val scope = viewModelScope<br>    fun loadData() {<br>        scope.launch {<br>            val data = repository.getData()<br>            _state.value = data<br>        }<br>    }<br>}</pre><p><strong>3. Dispatchers:-<br></strong>A Dispatcher in Kotlin Coroutines decides which<em> </em><strong><em>thread</em></strong><em> or </em><strong><em>thread pool</em></strong> a coroutine runs on, ensuring the right work happens in the right place (UI work on Main, network on IO, and heavy computation on Default)<br>Some Common Dispatchers are:-</p><p><strong>a. Dispatchers.Main</strong></p><pre>fun main() = runBlocking {<br>    launch(Dispatchers.Main) {<br>        println(&quot;Running on Main (UI) thread: ${Thread.currentThread().name}&quot;)<br>    }<br>}<br>output:<br>Running on Main (UI) thread: main</pre><p>It Runs coroutines on the <strong>Main (UI) thread</strong>.<br>It is Best for tasks that update the <strong>UI</strong> (Android views, Compose, etc).<br>It Should not be used for heavy operations (it may block the UI).</p><p><strong>b. Dispatchers.IO</strong></p><pre>fun main() = runBlocking {<br>    launch(Dispatchers.IO) {<br>        println(&quot;IO dispatcher: ${Thread.currentThread().name}&quot;)<br>        // simulate network or database<br>        delay(1000)<br>        println(&quot;Finished IO work on: ${Thread.currentThread().name}&quot;)<br>    }<br>}<br>output:<br>IO dispatcher starts on: DefaultDispatcher-worker-1<br>IO dispatcher resumes on: DefaultDispatcher-worker-1</pre><p>It is optimised for <strong>disk or network I/O operations</strong>.<br>Used for <strong>database calls</strong>, <strong>file read/write</strong>, <strong>API calls</strong>, etc.</p><p><strong>c. Dispatchers.Default</strong></p><pre>fun main() = runBlocking {<br>    launch(Dispatchers.Default) {<br>        println(&quot;Default dispatcher on: ${Thread.currentThread().name}&quot;)<br>        val sum = (1..10).sum()<br>        println(&quot;Calculated sum = $sum on: ${Thread.currentThread().name}&quot;)<br>    }<br>}<br>output:<br>Default dispatcher on: DefaultDispatcher-worker-2<br>Calculated sum = 55 on: DefaultDispatcher-worker-2</pre><p>It is used for <strong>CPU-intensive tasks</strong> (sorting, parsing JSON, large computations).<br>It uses a shared pool of background threads.<br>When you launch a coroutine with <strong>Dispatchers.Default</strong> or <strong>Dispatchers.IO</strong>, Kotlin uses a <strong>thread pool</strong> (a group of reusable background threads).<br>Each thread in that pool gets a name like:<br>DefaultDispatcher-worker-1<br>DefaultDispatcher-worker-2<br>DefaultDispatcher-worker-3 … etc.<br><strong>Note:- </strong>the <strong>coroutine thread pool size depends on the number of CPU cores</strong> of the device.</p><p><strong>d. Dispatchers.Unconfined</strong></p><pre>fun main() = runBlocking {<br>    launch(Dispatchers.Unconfined) {<br>        println(&quot;Unconfined starts on: ${Thread.currentThread().name}&quot;)<br>        delay(2000)//delay of 2 seconds.<br>        println(&quot;Unconfined resumes on: ${Thread.currentThread().name}&quot;)<br>    }<br>}<br>output:<br>Unconfined starts on: main<br>Unconfined resumes on: kotlinx.coroutines.DefaultExecutor<br>(we can see, that after delay of 2 seconds, <br>the coroutine has lost it&#39;s current thread. And has resumed in different thread.(It&#39;s not ideal)))</pre><p>It starts coroutine in the <strong>caller thread</strong>, but resumes it in the thread determined by the <strong>suspending function</strong>.<br>It is <strong>rarely</strong> <strong>used</strong> in Android because behaviour can be <strong>unpredictable</strong>.</p><p><strong>e. Inherited Dispatcher</strong></p><pre>fun main() = runBlocking {<br>    launch {  // inherits runBlocking dispatcher (main thread)<br>        println(&quot;No dispatcher → running on: ${Thread.currentThread().name}&quot;)<br>    }<br>}<br>output:<br>No dispatcher → running on: main</pre><p>If <strong>no</strong> dispatcher is specified, the coroutine <strong>inherits</strong> the dispatcher from its parent scope (i.e. runBlocking{…}).<br>Example:in above code, runBlocking {...} uses the <strong>current thread</strong> as default. So launch {...} will inherit it’s parent’s dispatcher.</p><p><strong>Suspend function :-</strong></p><pre>suspend fun fetchUserData(): String {<br>    // Simulating a long task (e.g., network call)<br>    delay(1500)//1.5 second delay  <br>    return &quot;User data loaded&quot;<br>}<br><br>fun main() = runBlocking {<br>    println(&quot;Fetching started on ${Thread.currentThread().name}&quot;)<br>    // Calling suspending function inside a coroutine<br>    val result = fetchUserData()<br>    println(&quot;Result: $result&quot;)<br>    println(&quot;Fetching finished on ${Thread.currentThread().name}&quot;)<br>}<br>output:<br>Fetching started on main<br>Result: User data loaded<br>Fetching finished on main</pre><p>A <strong>suspend function</strong> in Kotlin is a function marked with suspend that can <strong>pause</strong> its execution <strong>without</strong> blocking a thread, and <strong>resume</strong> later, enabling efficient concurrency.</p><blockquote>Now that you’ve seen how coroutines work, try experimenting with small examples — launch a few tasks, try different dispatchers, and observe how they run. Hands-on practice will solidify the concepts far better than theory alone. In upcoming articles, we will learn about some advance methods and use-cases of coroutines. And most important, <strong>Keep your rainforest green and shiny</strong>😀</blockquote><p>Stay tuned for more…<br><a href="http://www.linkedin.com/in/shashi-shekhar-mishra-150565bb">LinkedIn</a>, <a href="https://medium.com/@shekhar_mishra">Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18e978ceb712" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From App to APK: what is a Work Manager? Why it’s used?]]></title>
            <link>https://medium.com/@shashishekhar93/from-app-to-apk-what-is-a-work-manager-why-its-used-ca54f300e505?source=rss-4b706ed94a09------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca54f300e505</guid>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Shashi Shekhar Mishra]]></dc:creator>
            <pubDate>Sat, 16 Aug 2025 07:08:23 GMT</pubDate>
            <atom:updated>2025-08-16T07:08:23.239Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*HieIO36nbKnE8_A7DejJZw.png" /></figure><p>In our journey through the Android ecosystem, exploring the <strong>dense equatorial rainforest</strong>, let’s venture deeper and talk about the <strong>WorkManager — </strong>the <strong>rainforest’s root system</strong> for your Android app — invisible, tireless, and keeping everything alive even when no one’s looking. Running important jobs reliably, no matter the time, weather, or whether the app is even open.</p><h3>What is WorkManager ?</h3><p><strong>WorkManager</strong> is a tool from <strong>Android Jetpack</strong> that lets you run <strong>background</strong> <strong>tasks</strong> <strong>that must be done</strong>, even if:</p><p>The app is closed.<br>The device restarts.<br>The system kills your app temporarily.<br>Think of it as a <strong>to-do list manager</strong> for your app — it never forgets a task until it’s done.</p><h3>When to use it ?</h3><p>Use WorkManager when:</p><p>You want the task to run <strong>eventually</strong> (not immediately).<br>The task is <strong>important</strong> and <strong>must</strong> finish.<br>You may have conditions like “run only on Wi-Fi” or “only when charging.” etc.<br><strong>Examples include :-</strong></p><p><strong>Upload crash logs</strong> when the user next connects to Wi-Fi.<br><strong>Sync app data</strong> (contacts, messages, documents) in the background.<br><strong>Backup photos</strong> to the cloud only when the phone is charging.<br><strong>Send a reminder notification</strong> every morning at 8 AM.<br><strong>Refresh weather data</strong> every 3 hours.</p><p>❌ Not good for: Immediate, short tasks (use coroutines or foreground services instead).</p><p><strong>Let’s learn about different functions and properties of this class..</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwCF2XGPtaK-AhWFEMtpyA.png" /></figure><p>Here, <br>Worker → Base class in WorkManager for running background work in a separate thread.</p><p><strong>Constructor Parameters:<br></strong><strong>context:Context</strong> → Gives access to app resources, DB, etc.<br><strong>params: WorkerParameters</strong>→ Holds info about the current work request (input data, tags, etc.).</p><p><strong>Main Methods:<br></strong><strong>doWork()</strong> → Runs the background task;<br>returns Result.success(), Result.failure(), or Result.retry().<br><strong>onStopped()</strong> → Called if the work is cancelled before completion.</p><p><strong>Result Types:<br></strong><strong>Result.success()</strong> → Task finished successfully.<br><strong>Result.failure()</strong> → Task failed and won’t retry.<br><strong>Result.retry()</strong> → Task failed but will be tried again.<br><strong>Note</strong> :- We can return <strong>only one</strong> <strong>result</strong> <strong>type</strong> according to the demand of the request.</p><pre>class Module3Worker(context: Context, params: WorkerParameters) : Worker(context, params) {<br>    override fun doWork(): Result {<br>        val result : Result<br>        val randomNumber: Int = Random.nextInt(3)<br>        Log.d(ContentValues.TAG, &quot;doWork: randomNumber = $randomNumber&quot;)<br>        when (randomNumber) {<br>            0 -&gt; {<br>                runSomeTask(randomNumber)<br>                result = Result.failure()<br>            }<br>            1 -&gt; {<br>                runSomeTask(randomNumber)<br>                result = Result.success()<br>            }<br>            else -&gt; {<br>                runSomeTask(randomNumber)<br>                result = Result.retry()<br>            }<br>        }<br>        return result<br>    }<br>    private fun runSomeTask(status: Int) {<br>        Thread.sleep(2000)<br>        when (status) {<br>            0 -&gt; {<br>                Log.d(ContentValues.TAG, &quot;Task Failed&quot;)<br>            }<br>            1 -&gt; {<br>                Log.d(ContentValues.TAG, &quot;Task Completed&quot;)<br>            }<br>            else -&gt; {<br>                Log.d(ContentValues.TAG, &quot;Retrying Task&quot;)<br>            }<br>        }<br>}</pre><p>In above code, I have returned different result on different request. I have segregated the requests using a random number.</p><p><strong>Note</strong> that, if the result is Result.retry(), worker will again enqueue my request for re-execution after some seconds delay.<br>Now, <br>in my MainActivity.kt -&gt; onCreate() method, I will create a one time work request and add it to my workManager instance.</p><pre> private val workManager = WorkManager.getInstance(this)<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        doMyWork()<br>    }<br><br>    private fun doMyWork() {<br>        val request = OneTimeWorkRequest.Builder(Module3Worker::class.java)<br>            .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())<br>            .build()<br>        workManager.enqueue(request)<br>    }</pre><p>To make a periodic work request, I will create a PeriodicWorkRequest. Here I will have to specify the periodicity of time in my Builder by passing <strong>repeatInterval:Long</strong> and <strong>repeatIntervalTimeUnit:TimeUnit.</strong></p><pre> val request = PeriodicWorkRequest.Builder(Module3Worker::class.java, 5, TimeUnit.SECONDS)<br>            .setConstraints(<br>                Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()<br>            )<br>            .setBackoffCriteria(BackoffPolicy.LINEAR, 1000, TimeUnit.SECONDS)<br>            .build()<br>        workManager.enqueue(request)<br><br>        workManager.getWorkInfoByIdLiveData(request.id).observe(this) {<br>            if (it != null) {<br>                printStatus(it.state.name)<br>            }<br>        }</pre><p>In above code snippet, we can se a method getWorkInfoByIdLiveData()<br>Every work request has a <strong>unique ID</strong> (UUID) when you create it.<br>Pass that ID into getWorkInfoByIdLiveData() to get a <strong>LiveData&lt;WorkInfo&gt;</strong> object.<br>Observe the LiveData — it will emit updates whenever the work’s state changes.</p><p>It’s useful when you want your <strong>UI to update automatically</strong> as the work runs, succeeds, fails, or retries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*L1koctJD9quMzLT1wYzMvw.png" /><figcaption>Periodic request Constraints</figcaption></figure><p>Periodic Request can have these types of constraints when setConstraints() function comes in action.</p><p>So We have covered almost all the basics of Work Manager. We are ready to use it to solve our complex and long running scheduled operations. Best part of the Work Manager is that, it runs even if the app is removed from recent Apps Stack.😀</p><p>Stay tuned for more…<br><a href="http://www.linkedin.com/in/shashi-shekhar-mishra-150565bb">LinkedIn</a>, <a href="https://medium.com/@shekhar_mishra">Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca54f300e505" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From App to APK: what is a Service? Why it’s used?]]></title>
            <link>https://medium.com/@shashishekhar93/from-app-to-apk-what-is-a-service-why-its-used-a931ee08bc46?source=rss-4b706ed94a09------2</link>
            <guid isPermaLink="false">https://medium.com/p/a931ee08bc46</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[kotlin-for-android]]></category>
            <dc:creator><![CDATA[Shashi Shekhar Mishra]]></dc:creator>
            <pubDate>Fri, 15 Aug 2025 03:13:37 GMT</pubDate>
            <atom:updated>2025-08-17T15:29:09.036Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TySRST2TSmlTv11piPpkSw.png" /></figure><p>In the dense, vibrant ecosystem of an <strong>equatorial rainforest</strong>, life is always in motion. Bright parrots flash through the canopy, jaguars prowl silently, and towering trees stretch towards the sunlight. But while these visible creatures grab our attention, the <strong>rainforest’s survival</strong> actually depends on <strong>unseen forces</strong> — like the <strong>roots</strong> that <strong>draw</strong> water from deep underground, <strong>fungi</strong> that <strong>recycle</strong> nutrients, and <strong>insects</strong> that <strong>pollinate</strong> in the background.</p><p>Similarly, in the <strong>ecosystem of an Android app</strong>, not everything important happens on the screen. Beneath the shiny UI and user interactions, there are <strong>silent, tireless workers</strong> ensuring everything <strong>runs</strong> <strong>smoothly</strong> — fetching data, playing music, uploading files. These workers are the <strong>Service components</strong> of Android — essential, quiet, and often invisible, but critical for the app’s survival in the wild world of devices.</p><p><strong>What is a Service? <br></strong>A <strong>Service</strong> is <strong>Top Level</strong> Android component that runs <strong>in the background</strong> to perform <strong>long-running operations</strong> without a user interface.</p><p>It <strong>does not</strong> interact directly with the user.<br>It Can run <strong>even if the user switches to another app</strong>.<br>It is Ideal for <strong>background tasks</strong> like :-<br>1. Playing audio.<br>2. Uploading/downloading files.<br>3. Fetching data from a server.<br>4. Running scheduled jobs.</p><p>Other Top Level Components being <a href="https://medium.com/@shekhar_mishra/from-app-to-apk-what-is-an-activity-what-is-activity-lifecycle-d808d8efba8f"><strong>Activities</strong></a>, <strong>Content Providers</strong> and <strong>Broadcast Receivers</strong>.</p><p><strong>LifeCycle of Service<br></strong>A Service lifecycle is simpler than other component lifecycles. Let’s see here:-<br><strong>onCreate()</strong> → Called when the service is first created.<br><strong>onStartCommand()</strong> → Called each time the service is started.This Method runs on UI Thread.<br><strong>onBind()</strong> → Called when a component binds to the service.<br><strong>onDestroy()</strong> → Called when the service is destroyed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IrM7mcgNhou8anWaeRfunA.png" /><figcaption>Service class</figcaption></figure><p>The Service class is inherited with Service() class, Which is the component of <strong>android.app.Service</strong> package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*0Cge3RarAy_GUw4C0fviDA.png" /></figure><p>After creating DemoService.kt, We need to declare it in Manifest.xml like above.</p><p><strong>Types Of Services</strong></p><p>There are 3 types of Services in Android system as :- <br>1. Background Services.<br>2. Foreground Services.<br>3. Bound Services.</p><p><strong>Background Services<br></strong>Runs without the direct interaction and no persistant notification.<br>Used for short, light-weight background tasks<br>eg:- <strong>syncing whatsApp messages</strong> in the background when user is not interacting with app, <strong>Syncing Emails</strong> etc.<br><strong>But,</strong> after some time, there came a restriction…</p><p><strong>Before Android 8.0:</strong> You could freely start a background Service even if your app was not in the foreground.<br><strong>From Android 8.0+<br></strong>If your app is <strong>not in the foreground</strong>, you <strong>cannot</strong> freely run an unlimited-time background service.<br>Apps in the background get a <strong>few minutes of execution</strong> before the system stops the service.</p><p><strong>Now</strong>, Since plain background services are restricted:<br><strong>WorkManager</strong> → For guaranteed background work (even after reboot).<br><strong>JobScheduler</strong> → For scheduled or deferred tasks.<br><strong>Foreground Service</strong> → For visible, user-aware tasks like music playback or tracking.</p><p>Let’s see, how to start a service:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*LM8fXooGtAm4qvM_cQwJeQ.png" /></figure><p>Simply use the <strong>startService()</strong> method with parameters as current <strong>context</strong> and the our service <strong>class name</strong>.The <strong>Intent</strong> will launch the our service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*v8jpVuncbdH2MjBC9UrzWg.png" /></figure><p>Use stopService() method to stop the running service. The parameters will be same.<br>If you want your service to stop automatically when the work is completed, You need to use stopSelf() in onStartCommandMethod().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*T5YRYF9cT6G4NGNzMcKf_A.png" /></figure><p><strong>Foreground Services<br></strong>If you need long-running work while your app is in the <strong>background</strong>, you <strong>must</strong> use a <strong>Foreground Service</strong> with a <strong>persistent notification</strong>.<br>This ensures the user knows something is running, and Android won’t kill it as quickly.<br>eg:- Playing music using <strong>Spotify/Gaana</strong> — the music keeps playing even if the user opens another app, and a notification is always visible.</p><p>To Launch a Foreground Service, We need several components :-</p><p>In DemoService.kt Class:-<br><strong>startForeground(id:Int, notification:Notification) </strong>Method.<strong><br></strong>A <strong>Notification</strong> <strong>Object</strong> <br>A <strong>Notification</strong> <strong>Channel</strong><br>A <strong>Pending</strong> <strong>Intent</strong>.</p><p>In MainActivity.kt:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*-yQCpcv-jybyJR_wpcGqzg.png" /></figure><p><strong>startForegroundService(intent service) <br></strong>As we can that this method requires a condition to check if the API version is greater or equal to API-26, Android 8.0.(Because we’ve already learnt that Foreground Services came into action after android 8.0)</p><p>Now, to stop the foreground service, we simply call stopService() in MainActivity.kt.<br>We can also stop it from service class using <strong>stopForeground(STOP_FOREGROUND_REMOVE) . <br></strong>This will stop the service and remove the notification.</p><p><strong>Bound Services<br></strong>A <strong>bound service</strong> works <strong>only when another component (like an Activity, Fragment, or another Service) is connected to it</strong>.<br>It’s life depends on the lifecycle of the component it’s bound to.<br><strong>eg:- </strong><br><strong>phone call</strong> — you “pick up” to talk (bind), and when you “hang up” (unbind), the service stops.<br><strong>music app</strong> where your Activity binds to the service to play, pause, or skip songs, and the service stops when the Activity closes.</p><p>Top stop the bound service <strong>unbindService(serviceConnection) </strong>method is used.</p><p>“Just like some creatures in a rainforest quietly keep the jungle alive, Android services work in the background to keep apps running smoothly, even when you’re not looking at them.”</p><p>In Upcoming separate articles, we will dive deeper in <strong>foreground</strong> <strong>services(practical with notifications) and Bound Services </strong>and their alternative such as <a href="https://medium.com/@shekhar_mishra/from-app-to-apk-what-is-a-work-manager-why-its-used-ca54f300e505">WorkManager</a>.</p><p>Stay tuned for more…<br><a href="http://www.linkedin.com/in/shashi-shekhar-mishra-150565bb">LinkedIn</a>, <a href="https://medium.com/@shekhar_mishra">Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a931ee08bc46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From App to APK: what is an Activity, what is Activity Lifecycle.]]></title>
            <link>https://medium.com/@shashishekhar93/from-app-to-apk-what-is-an-activity-what-is-activity-lifecycle-d808d8efba8f?source=rss-4b706ed94a09------2</link>
            <guid isPermaLink="false">https://medium.com/p/d808d8efba8f</guid>
            <category><![CDATA[activity-life-cycle]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Shashi Shekhar Mishra]]></dc:creator>
            <pubDate>Tue, 29 Jul 2025 16:07:01 GMT</pubDate>
            <atom:updated>2025-07-30T02:44:44.615Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“Life is not measured by the number of breaths we take, but the moments that take our breath away.”<br></em>Same way, <strong>An Android activity’s life</strong> isn’t about how long it <strong>stays alive</strong> in memory — but about the moments it truly serves the <strong>user</strong> — when it’s <strong>Resumed</strong> and <strong>interactive</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BdKR9EdkTI93ud30gW7Wiw.png" /></figure><p><strong>In Android App development</strong>, an <strong>Activity</strong> is one of the most important components. Simply put, <strong>an Activity represents a single screen</strong> with which the user can interact.<br>An activity provides the window in which the app draws its <strong>UI</strong>. For example, when you open the Instagram App, your Feed is one entire activity. Now this activity contains a UI comprising of Buttons, Images etc.<br>When we click to some button or image, we simply switch to some another activity and vice-versa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ynYRjZh0Ku4OTJ3VwAM7w.png" /><figcaption>MainActivity.kt</figcaption></figure><p>Above image represents, what an activity class look likes in kotlin.<br>We can see Inheritance, a property of OOPs. We will study the concepts of OOPs in upcoming article.<br>we have already seen our <a href="https://medium.com/@shekhar_mishra/from-app-to-apk-understanding-your-android-project-folder-d9e190c19e32">previous article</a> ,how activity is declared in AndroidManifest. Let’s dive in further to deep in workflow of activity class.</p><p>An <strong>Activity</strong>:<br>Is a subclass of android.app.Activity (or ComponentActivity).<br>Controls the <strong>UI and behaviour</strong> of a screen in an app.<br>Acts as an <strong>entry point</strong> for user interactions.<br>Can start another activity using <strong>Intents.</strong></p><p><strong>Activity Lifecycle:</strong><br>Each activity goes through a series of <strong>lifecycle states</strong> from creation to destruction. Android provides <strong>lifecycle methods</strong> to handle this transition smoothly.</p><h3>Lifecycle Methods:</h3><p>Each activity goes through a series of <strong>lifecycle states</strong> from creation to destruction. We can see the images below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*fnlA51KMDVY34QRlGmCD4A.png" /></figure><h3>When Are These Methods Called?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*F0nF74Ny09r684RQQ0Pjbg.png" /></figure><p>Android activities go through a lifecycle with distinct states, each reflecting the activity’s visibility and interaction status for the user.Let’s see below.<br>Note: It is ideal to do practical on your favorite in your smart phone. I prefer <strong>medium😀</strong></p><ul><li><strong>Created</strong>: The activity is being initialised. The system calls onCreate(). Here, you set up UI elements and prepare resources, but the activity isn’t visible yet.</li><li><strong>Started</strong>: Called after onStart(). The activity is now visible to the user but not yet interactive (for example, another activity may be in the foreground but partially transparent).</li><li><strong>Resumed</strong> (Active/Running): The activity is in the foreground and the user can interact with it. This state begins after onResume() is called. This is where most user input and UI interactions happen.</li><li><strong>Paused</strong>: The activity is still partially visible, but another activity is in the foreground and partially covers it (like a dialog). The system calls onPause(). Heavy resources or tasks should be released or paused here, since the user can no longer interact with the app, but it’s not fully hidden.</li><li><strong>Stopped</strong>: The activity is completely hidden and not visible to the user. It is no longer interacting with the user, but its state, resources, and view hierarchy remain in memory. This follows onStop() and can be brought back to <em>Started</em> or <em>Resumed</em> if the user returns.</li><li><strong>Restarted</strong>: If a stopped activity is about to become visible again, the system calls onRestart(). After this, it follows the same path as a new start (onStart() and onResume()).</li><li><strong>Destroyed</strong>: The activity is finished and removed from memory; this occurs either because the user closes the activity, navigates back, or the system needs to free resources. The onDestroy() method is called before final removal.</li></ul><p>Understanding the activity lifecycle is essential for building stable, responsive, and user-friendly Android applications. We have completed this section successfully.<br>Stay tuned for more…<br><a href="http://www.linkedin.com/in/shashi-shekhar-mishra-150565bb">LinkedIn</a>, <a href="https://medium.com/@shekhar_mishra">Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d808d8efba8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From App to APK: Understanding Your Android Project Structure.]]></title>
            <link>https://medium.com/@shashishekhar93/from-app-to-apk-understanding-your-android-project-structure-ff9435e8fcc2?source=rss-4b706ed94a09------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff9435e8fcc2</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Shashi Shekhar Mishra]]></dc:creator>
            <pubDate>Sun, 20 Jul 2025 08:07:03 GMT</pubDate>
            <atom:updated>2025-07-20T08:07:03.722Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yG6Ke8-Yk9s2hGuTZQy_A.png" /></figure><p>In <a href="https://medium.com/@shekhar_mishra/from-app-to-apk-understanding-your-android-project-folder-d9e190c19e32"><strong>Previous Article</strong></a><strong> , </strong>we’ve covered the <strong>Manifest file</strong>, let’s move deeper and explore into the dense canopy of our Equatorial Rain Forest <strong>i.e.</strong> <strong>heart of your Android project</strong> — the <strong>java/kotlin source folders</strong>, the <strong>res (resources) directory</strong>, and the key components inside them that bring your app to life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bY-NZpBbwN-4BKvPvn08ug.png" /><figcaption>project structure(left)</figcaption></figure><p>In above image, we can see various directories like <strong>kotlin+java, res</strong> etc.<br>Let’s discuss it one by one.<br><strong>Kotlin+java </strong>directory contains various folders and sub-folders. <br>This folder contains <strong>three main types of packages</strong>:<br>1. <strong>Main Code (</strong>mainly contains of .java and .kt production files<strong>)<br></strong>2. <strong>Test Code</strong>(Used to write test codes to test app features our emulator.)<br>3. <strong>Android Instrumented Test Code </strong>(Used to write test codes to test app features on actual android device.)<br>*We are going to learn about test cases on our upcoming articles.</p><p>Let’s jump on next directory i.e. <strong>res</strong> (resources directory).<br>res contains subfolders such as:</p><p><strong>drawable/</strong> – Stores bitmap images, vector assets, and shape XMLs used in UI elements.</p><p><strong>layout/</strong> – Contains XML files that define UI layouts for your app&#39;s activities and fragments. <br>In case of Jetpack Compose, XML layouts will rarely be used as we will create our app’s layout solely on jetpack-compose.</p><p><strong>values/</strong> – Holds XML files like strings.xml, colors.xml, and themes.xml for storing resources as key-value pairs.</p><p><strong>mipmap/</strong> – Used for app launcher icons in various resolutions for different screen densities.</p><p><strong>menu/</strong> – Contains XML files that define app menus and toolbars.|</p><p><strong>anim/</strong> – Holds XML files that define tween animations (like fade, scale, etc.).</p><p><strong>animator/</strong> – Stores property animation files (ObjectAnimator).</p><p><strong>raw/</strong> – Used to store arbitrary raw files like audio, video, or other media.</p><p><strong>font/</strong> – Stores custom font files (TTF/OTF) for use in UI elements.</p><p><strong>xml/</strong> – Contains general-purpose XML files like preferences, backup_rules.xml, etc.</p><p><strong>color/</strong> – Defines color state lists for different UI states (like pressed, focused).</p><p><strong>transition/</strong> – Holds transition XMLs for motion/scene transitions between layouts.</p><p>We are going to delve in these folders and files while gradually developing our demo apps. There I’ll show you the usecases of these files and folders.</p><p>We tried to understand our complete project structure. Now it will be much easier for us to understand the upcoming developments in our apps.</p><p>Stay tuned for more.<br><a href="http://www.linkedin.com/in/shashi-shekhar-mishra-150565bb">LinkedIn</a>, <a href="https://medium.com/@shekhar_mishra">Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff9435e8fcc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>