<?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 Shreyash Pattewar on Medium]]></title>
        <description><![CDATA[Stories by Shreyash Pattewar on Medium]]></description>
        <link>https://medium.com/@shreyashp47?source=rss-7fd126566ef1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Shreyash Pattewar on Medium</title>
            <link>https://medium.com/@shreyashp47?source=rss-7fd126566ef1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 03:52:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shreyashp47/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[Coroutines vs Threads — Why Lightweight?]]></title>
            <link>https://medium.com/@shreyashp47/coroutines-vs-threads-why-lightweight-24b9cbf80d59?source=rss-7fd126566ef1------2</link>
            <guid isPermaLink="false">https://medium.com/p/24b9cbf80d59</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Shreyash Pattewar]]></dc:creator>
            <pubDate>Tue, 29 Jul 2025 07:39:32 GMT</pubDate>
            <atom:updated>2025-07-31T11:35:08.670Z</atom:updated>
            <content:encoded><![CDATA[<h3>Coroutines vs Threads — Why Lightweight?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*COMgNh2NWh4zaG2mrosn3g.png" /></figure><p>As Android developers, we often hear that “<strong>coroutines are lightweight</strong>” and “<strong>threads are expensive</strong>.” But what does that really mean?</p><p>Coroutines are one of Kotlin’s most powerful features for handling <strong>asynchronous</strong> and <strong>concurrent</strong> operations. They allow you to run background tasks (like network requests, database operations, timers, etc.) <strong>without blocking the main thread</strong>, while keeping your code readable and maintainable.</p><p>Unlike traditional threading, where each operation needs a new thread (which consumes a lot of system memory), coroutines can run <strong>hundreds of thousands of tasks</strong> with just a few threads in the background. They achieve this through <strong>suspending functions</strong>, which pause and resume execution without occupying thread resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FJsVQ5bzvrhYZPlANqdTeQ.png" /></figure><h3>Why are coroutines important in Android?</h3><ul><li>Android apps need to remain <strong>responsive</strong>. Blocking the main thread causes UI freezes or ANRs.</li><li>Many Android tasks (API calls, local storage, animations) need to be <strong>run in the background</strong>.</li><li>With coroutines, you can write <strong>asynchronous code that looks synchronous</strong>, making it easier to read and debug.</li></ul><p>To understand how they compare with threads in a practical scenario, I built a small Android app that launches thousands (even 100,000) of tasks using both threads and coroutines. The goal: to compare performance, responsiveness, and memory usage — and to <strong>see why coroutines are called “lightweight”</strong>.</p><h4>1. Launching 100K Threads</h4><pre>private fun launchThreads() {<br>    val totalThreads = 100_000<br>    val counter = AtomicInteger(0)<br>    binding.tvResultThreads.text = &quot;Status: Launched&quot;<br>repeat(totalThreads) {<br>        Thread {<br>            Thread.sleep(5000L)<br>            if (counter.incrementAndGet() == totalThreads) {<br>                runOnUiThread {<br>                    binding.tvResultThreads.text = &quot;Status: Completed&quot;<br>                }<br>            }<br>        }.start()<br>    }<br>}</pre><ul><li>Launches 100,000 real threads.</li><li>Each thread sleeps for 5 seconds.</li><li>Consumes huge memory.</li><li>May freeze UI or crash on low-end devices.</li></ul><h4>2. Launching 100K Coroutines</h4><pre>private fun launchCoroutines() {<br>    val totalCoroutines = 100_000<br>    val counter = AtomicInteger(0)<br>  binding.tvResultCoroutines.text = &quot;Status: Launched&quot;<br>    repeat(totalCoroutines) {<br>        GlobalScope.launch {<br>            delay(5000L)<br>            if (counter.incrementAndGet() == totalCoroutines) {<br>                runOnUiThread {<br>                    binding.tvResultCoroutines.text = &quot;Status: Completed&quot;<br>                }<br>            }<br>        }<br>    }<br>}</pre><ul><li>Launches 100,000 coroutines.</li><li>Each coroutine suspends using delay(), without blocking threads.</li><li>Runs smoothly even on low-end devices.</li><li>Very efficient in terms of memory and CPU usage.</li></ul><h4>3. Launching with 4 Threads (Thread Pool)</h4><pre>private fun launch4Threads() {<br>    numThread4 = AtomicInteger(0)<br>    val threadPool = Executors.newFixedThreadPool(4)<br>    val startTime = System.currentTimeMillis()<br>        repeat(4) {<br>        threadPool.execute {<br>            repeat(2500) {<br>                longRunningTask4(startTime)<br>            }<br>        }<br>    }<br>}<br><br>private fun longRunningTask4(startTime: Long) {<br>    if (numThread4.incrementAndGet() == 10_000) {<br>        val timeTaken = System.currentTimeMillis() - startTime<br>        Log.d(TAG, &quot;Result using 4 thread: $timeTaken ms&quot;)<br>        runOnUiThread {<br>            binding.tvResult4.text = &quot;Result: ${timeTaken}ms&quot;<br>        }<br>    }<br>}</pre><ul><li>Uses a fixed pool of <strong>4 threads</strong>.</li><li>Launches 10,000 tasks, 2500 on each thread.</li><li>Threads are reused by the executor.</li><li>Takes more time than 40 threads, but efficient.</li></ul><h3>4. Launching with 40 Threads (Thread Pool)</h3><pre>private fun launch40threads() {<br>    numThread40 = AtomicInteger(0)<br>    val threadPool = Executors.newFixedThreadPool(40)<br>    val startTime = System.currentTimeMillis()<br>    repeat(10_000) {<br>        threadPool.execute {<br>            longRunningTask40(startTime)<br>        }<br>    }<br>}<br>private fun longRunningTask40(startTime: Long) {<br>    if (numThread40.incrementAndGet() == 10_000) {<br>        val timeTaken = System.currentTimeMillis() - startTime<br>        Log.d(TAG, &quot;Result using 40 thread: $timeTaken ms&quot;)<br>        runOnUiThread {<br>            binding.tvResult40.text = &quot;Result: ${timeTaken}ms&quot;<br>        }<br>    }<br>}</pre><ul><li>Uses a pool of <strong>40 threads</strong>.</li><li>Each of the 10,000 tasks is submitted directly.</li><li><strong>Thread reuse improves performance</strong>.</li><li>If you click onLaunchUsing40Threads multiple times, execution becomes faster — because <strong>existing threads are reused</strong> by the JVM.</li></ul><h3>Why Coroutines Are Better</h3><ol><li><strong>Memory Efficient</strong> — You can launch 100,000 coroutines with ease. Threads will likely crash.</li><li><strong>Non-blocking</strong> — Coroutines use delay() (non-blocking), threads use sleep() (blocking).</li><li><strong>Scalable</strong> — Coroutines can scale to massive numbers without system strain.</li><li><strong>Cleaner Code</strong> — Sequential, readable, and easier to maintain.</li><li><strong>Thread Pool Reuse</strong> — Thread pools (like in launch40Threads) perform better with repeated launches.</li></ol><p>To make it easier to understand, I recorded a short video demonstrating the app in action.</p><p>In the video, you’ll see:</p><ul><li>How the app behaves when launching 100K threads vs coroutines</li><li>The performance difference between 4-thread and 40-thread pools</li><li>How repeated launches with thread pools get faster over time due to thread reuse</li></ul><p>Seeing the UI updates and timing results live makes the comparison much clearer.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FoxJ5kxKih3s%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FoxJ5kxKih3s%3Ffeature%3Dshare&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FoxJ5kxKih3s%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dedb18000ddffeeb638f0855b196a53/href">https://medium.com/media/4dedb18000ddffeeb638f0855b196a53/href</a></iframe><h4>So, Why Are Coroutines Lightweight?</h4><ol><li><strong>They don’t require a dedicated thread</strong>:<br>Unlike threads, coroutines can be suspended without blocking the thread they run on. This allows multiple coroutines to share a small number of threads.</li><li><strong>Minimal memory footprint</strong>:<br>A thread typically uses around 1 MB of stack memory, but a coroutine needs only a few KB to store its state. That’s why you can create <strong>tens of thousands</strong> of coroutines without crashing your app.</li><li><strong>No expensive context switches</strong>:<br>Threads require kernel-level context switching (saving CPU registers, stack pointers, etc.), which is slow. Coroutines switch in user space with minimal cost.</li><li><strong>Dispatcher reuses threads efficiently</strong>:<br>In Kotlin, the Dispatchers.Default or Dispatchers.IO use a shared thread pool. So even 100,000 coroutines might run on just a handful of threads.</li></ol><h3>Conclusion</h3><p><strong><em>Threads are heavyweight workers — they do the job but consume a lot.<br>Coroutines are smart assistants — light, fast, and highly efficient.</em></strong></p><p>If you’re still relying on manual threads or blocking code, now is the best time to switch to Kotlin coroutines for better performance and cleaner architecture.</p><h3>GitHub Repository</h3><p><a href="https://github.com/shreyashp47/Coroutines-internals">https://github.com/shreyashp47/Coroutines-internals</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24b9cbf80d59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android’s 16KB Memory Page Size Explained: What It Means and How to Fix]]></title>
            <link>https://medium.com/@shreyashp47/androids-16kb-memory-page-size-explained-what-it-means-and-how-to-fix-3a383b3b4691?source=rss-7fd126566ef1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a383b3b4691</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[google-play-console]]></category>
            <category><![CDATA[memory-optimization]]></category>
            <category><![CDATA[android-ndk]]></category>
            <dc:creator><![CDATA[Shreyash Pattewar]]></dc:creator>
            <pubDate>Mon, 28 Jul 2025 06:48:42 GMT</pubDate>
            <atom:updated>2025-07-28T06:58:30.748Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fNWdOqIA0c9nzqdzaA0aWQ.png" /></figure><p>As Android continues to improve system-level performance, Google has started enforcing a significant change that affects many apps — <strong>mandatory support for 16KB memory page sizes</strong>. This change mostly affects apps using <strong>native code</strong> or libraries that package native .so files.</p><p>This policy can impact your app’s compatibility on new devices — including installation failures and runtime crashes — if not handled properly.</p><h3>What Is Android’s 16KB Page Size?</h3><p>Traditionally, Android devices used <strong>4KB page size</strong>, which defines the unit of memory allocation. But with the evolution of hardware and system optimization, <strong>many new devices now use 16KB page sizes</strong>, and Android is moving toward making this the default on more devices.</p><p>According to <a href="https://developer.android.com/guide/practices/page-sizes">Google</a>, this transition comes with <strong>real performance benefits</strong>:</p><ul><li>App launch speed improves by <strong>3.16–30%</strong></li><li>System boots up faster by <strong>~8%</strong></li><li>Battery savings of around <strong>4.56%</strong></li><li>Camera starts accelerating by <strong>4.48–6.60%</strong></li></ul><blockquote><strong><em>Note:</em></strong><em> This optimization applies only to native (NDK) code — the C or C++ code compiled into </em><em>.so libraries. There is </em><strong><em>no impact on Java or Kotlin code</em></strong><em>.</em></blockquote><h3>Why This Matters to Developers?</h3><p>If your app includes or depends on .so libraries, and they are not compiled properly for 16KB alignment, your app may:</p><ul><li>Crash during launch on certain devices</li><li>Fail to install on devices with 16KB pages</li><li>Receive <strong>warnings in the Play Console</strong></li><li>Lose reach to a growing segment of Android users</li></ul><h3>Where to Check This in Google Play Console</h3><p>To see if your app includes incompatible native libraries:</p><ol><li>Go to your app on <strong>Google Play Console</strong></li><li>Navigate to: <strong>Release &gt; App Bundle Explorer</strong></li><li>Select the latest release version</li><li>Go to the <strong>“Memory page size”</strong> tab</li><li>Look for .so files marked with:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lad6qg0EN7J_NvrEFpSeyQ.png" /></figure><p>Or simply drag and drop your .apk file in Android Studio</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GT0lT7VWxunpRyXBdCT3bg.png" /></figure><h3>Libraries That May Affect Your App</h3><p>If your app includes any of the following libraries, it may be impacted by the 16KB page size policy. These libraries include native .so files that were previously not compatible and may lead to runtime crashes or install failures on modern Android devices.<strong> GIPHY SDK, Amazon IVS</strong>, <strong>SQLCipher, PDFTron, PDFLib</strong></p><p>In addition to these, other widely used libraries that include native code and may pose compatibility issues include:</p><ul><li><strong>FFmpeg</strong>-based libraries used for video/audio encoding and decoding.</li><li><strong>TensorFlow Lite</strong> (older versions) that include native ML inference code.</li><li><strong>OpenCV</strong> (especially if using prebuilt binary packages).</li><li><strong>ExoPlayer extensions</strong> that leverage native decoders.</li><li>Any <strong>custom </strong>.so<strong> libraries</strong> built from C/C++ without proper page size alignment.</li></ul><p>If your app uses any of these directly, or through another dependency, it’s critical to check your Play Console and update or rebuild accordingly.</p><h3>How to Make Your App 16KB-Compatible</h3><h4>1. Use the Latest NDK (r26+)</h4><p>Update your project to use <strong>NDK version r26 or newer</strong>, which supports building .so files aligned to 16KB pages.</p><h4>2. Update Third-Party Libraries</h4><p>Ensure that you are using the <strong>latest versions</strong> of native SDKs or libraries that support 16KB page size:</p><ul><li>Giphy SDK &gt;= 2.3.17</li><li>Amazon IVS &gt;= 1.42.0</li><li>For SQLCipher, consider building it yourself using the latest NDK until the maintainers provide an updated release.</li></ul><h4>3. Update Your Native Build Configurations</h4><p>If you write your own C/C++ code using <strong>CMake</strong>, add this line to enable 16KB page size:</p><pre>set(CMAKE_ANDROID_PAGE_SIZE 16384)</pre><p>For standalone builds or Android.mk files, refer to NDK r26 documentation for proper flags.</p><h4>4. Avoid Hardcoding Page Size</h4><p>If your code relies on hardcoded values like 4096 for memory operations, replace them with:</p><pre>sysconf(_SC_PAGESIZE)</pre><p>This ensures your code works dynamically on both 4KB and 16KB devices.</p><h4>5. Test on Devices or Emulators</h4><p>Use physical devices or Android 14+ emulators with 16KB support to test your builds before release.</p><h3>How to Manually Check .so Alignment</h3><p>You can inspect .so files locally using:</p><pre>readelf -l libexample.so | grep LOAD</pre><p>Check the <strong>Align</strong> column — it should read 0x4000 (16384 in decimal). If it shows 0x1000, the file is built for 4KB and will <strong>not</strong> work on 16KB-only devices.</p><h3>Summary</h3><ul><li>Google is moving Android toward <strong>16KB page size</strong> for performance reasons.</li><li>Native libraries (.so files) <strong>must be built or updated</strong> to support this page size.</li><li>Java/Kotlin-only apps are not impacted.</li><li>Use the <strong>latest NDK</strong>, <strong>upgrade libraries</strong>, and <strong>check Play Console warnings</strong>.</li><li>Rebuild or replace any incompatible .so files in your app.</li></ul><p>If your app includes native code — whether you wrote it or it’s from a third-party SDK — now is the time to check for 16KB compatibility and avoid runtime crashes or Play Store issues.</p><p>Have you faced installation crashes on Android 14+? Drop your experience or solution in the comments — let’s help the community prepare for the 16KB transition together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a383b3b4691" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SharedPreferences vs DataStore: A Clean Architecture Perspective]]></title>
            <link>https://medium.com/@shreyashp47/sharedpreferences-vs-datastore-a-clean-architecture-perspective-98dfe4c53505?source=rss-7fd126566ef1------2</link>
            <guid isPermaLink="false">https://medium.com/p/98dfe4c53505</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[data-storage]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Shreyash Pattewar]]></dc:creator>
            <pubDate>Sun, 13 Jul 2025 16:58:57 GMT</pubDate>
            <atom:updated>2025-07-13T17:25:31.532Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FEc8yxB0AV4ZJvc22xSSoQ.png" /></figure><p>Android development has come a long way — from AsyncTask and boilerplate-heavy activities to Kotlin Coroutinesand Jetpack Compose. One such evolution is the shift from SharedPreferences to DataStore.</p><p>In this post, I’ll walk through the key differences between the two, and how you can integrate DataStore using <strong>Clean Architecture</strong> and <strong>modern best practices</strong>, with code from one of my own projects.</p><h3>Why SharedPreferences Falls Short?</h3><p>SharedPreferences has been the go-to for small, persistent key-value storage in Android. But it comes with some limitations:</p><ul><li>Not thread-safe by default</li><li>Uses blocking I/O (can cause ANRs)</li><li>No support for Kotlin Coroutines or Flow</li><li>Error-prone in multi-threaded environments</li></ul><p>These limitations make SharedPreferences a risky choice for modern, coroutine-based apps.</p><h3>Why DataStore is Better</h3><p>DataStore is now <strong>recommended by Google</strong> as the preferred solution for small and consistent local data storage in Android apps.</p><p>DataStore, introduced by Jetpack, solves most of these problems:</p><ul><li><strong>Asynchronous</strong>: Built with Coroutines and Flow</li><li><strong>Thread-safe</strong>: No need to manage synchronization manually</li><li><strong>Resilient</strong>: Built-in corruption handling</li><li><strong>Extensible</strong>: Offers Preferences and Proto formats</li></ul><h3>Two Types of DataStore</h3><p><strong>1.Preferences DataStore</strong>:</p><ul><li>Key-value pairs, similar to SharedPreferences</li><li>Best for simple use cases</li></ul><p><strong>2.Proto DataStore</strong>:</p><ul><li>Stores typed, structured data using Protocol Buffers</li><li>Ideal for complex objects and type safety</li></ul><blockquote>While `Preferences DataStore` is easier to migrate to, `Proto DataStore` provides strong typing and better structure for larger or evolving datasets.</blockquote><h4>SharedPreferences Example:</h4><pre>// Save a value<br>val prefs = context.getSharedPreferences(&quot;settings&quot;, Context.MODE_PRIVATE)<br>prefs.edit().putBoolean(&quot;dark_mode&quot;, true).apply()<br>// Read a value<br>val darkMode = prefs.getBoolean(&quot;dark_mode&quot;, false)</pre><h4>DataStore Example (Preferences):</h4><pre>val DARK_MODE_KEY = booleanPreferencesKey(&quot;dark_mode&quot;)<br><br>// Read<br>val darkModeFlow: Flow&lt;Boolean&gt; = context.dataStore.data<br>    .map { prefs -&gt; prefs[DARK_MODE_KEY] ?: false }<br><br>// Write<br>suspend fun setDarkMode(enabled: Boolean) {<br>    context.dataStore.edit { prefs -&gt; prefs[DARK_MODE_KEY] = enabled }<br>}</pre><blockquote><em>This is just a basic example. In real apps, you’d wrap this inside a repository with Clean Architecture separation, just like in </em><a href="https://github.com/shreyashp47/DoTrack"><em>my GitHub repo</em></a><em>.</em></blockquote><h3>Clean Architecture + DataStore</h3><p>Here’s how you can integrate DataStore with Clean Architecture:</p><pre>DoTrack<br>├── app/                    # Presentation Layer<br>│   ├── ui/                 # Compose UI Components<br>│   ├── navigation/         # Navigation Logic<br>│   └── workmanager/        # Background Tasks<br>├── domain/                 # Business Logic Layer<br>│   ├── model/              # Domain Models<br>│   ├── repository/         # Repository Interfaces<br>│   └── usecase/            # Business Use Cases<br>├── data/                   # Data Layer<br>│   ├── local/              # Room Database<br>│   ├── repository/         # Repository Implementations<br>│   └── di/                 # Dependency Injection<br>└── core/                   # Shared Components<br>    ├── ui/                 # Common UI Components<br>    └── util/               # Utilities</pre><p>Each layer has a clear responsibility and can be unit tested in isolation.</p><h3>Real Use Case: Theme and Color Preferences</h3><p>In my app, I implemented PreferencesDataStore to store user-defined UI settings like: <a href="https://github.com/shreyashp47/DoTrack/blob/main/data/src/main/java/com/shreyash/dotrack/data/repository/UserPreferencesRepositoryImpl.kt"><em>/data/repository/UserPreferencesRepositoryImpl.kt</em></a></p><ul><li>Auto wallpaper toggle</li><li>Primary &amp; secondary wallpaper colors</li><li>Priority-based task colors</li></ul><h4>Preference Keys</h4><pre>object PreferencesKeys {<br>    val AUTO_WALLPAPER_ENABLED = booleanPreferencesKey(&quot;auto_wallpaper_enabled&quot;)<br>    val WALLPAPER_COLOR = stringPreferencesKey(&quot;wallpaper_color&quot;)<br>    val SECONDARY_WALLPAPER_COLOR = stringPreferencesKey(&quot;secondary_wallpaper_color&quot;)<br>    val HIGH_PRIORITY_COLOR = stringPreferencesKey(&quot;high_priority_color&quot;)<br>    val MEDIUM_PRIORITY_COLOR = stringPreferencesKey(&quot;medium_priority_color&quot;)<br>    val LOW_PRIORITY_COLOR = stringPreferencesKey(&quot;low_priority_color&quot;)<br>}</pre><h4>Reading Preferences (with Flow)</h4><pre>val autoWallpaperFlow: Flow&lt;Boolean&gt; = dataStore.data<br>    .catch { exception -&gt;<br>        if (exception is IOException) emit(emptyPreferences()) else throw exception<br>    }<br>    .map { preferences -&gt;<br>        preferences[PreferencesKeys.AUTO_WALLPAPER_ENABLED] ?: false<br>    }</pre><h4>Writing Preferences (Asynchronously)</h4><pre>suspend fun setAutoWallpaperEnabled(enabled: Boolean): Result&lt;Unit&gt; {<br>    return try {<br>        dataStore.edit { it[PreferencesKeys.AUTO_WALLPAPER_ENABLED] = enabled }<br>        Result.Success(Unit)<br>    } catch (e: Exception) {<br>        Result.Error(e)<br>    }<br>}</pre><h4>Interface Abstraction (Domain Layer)</h4><p><a href="https://github.com/shreyashp47/DoTrack/blob/main/domain/src/main/java/com/shreyash/dotrack/domain/repository/UserPreferencesRepository.kt"><em>/domain/repository/UserPreferencesRepository.kt</em></a></p><pre>interface UserPreferencesRepository {<br>    fun getAutoWallpaperEnabled(): Flow&lt;Boolean&gt;<br>    suspend fun setAutoWallpaperEnabled(enabled: Boolean): Result&lt;Unit&gt;<br>    // and more...<br>}</pre><h4>ViewModel Usage Example</h4><p><a href="https://github.com/shreyashp47/DoTrack/blob/main/app/src/main/java/com/shreyash/dotrack/ui/settings/SettingsViewModel.kt"><em>/dotrack/ui/settings/SettingsViewModel.kt</em></a></p><pre>@HiltViewModel<br>class SettingsViewModel @Inject constructor(<br>    private val getAutoWallpaperUseCase: GetAutoWallpaperUseCase,<br>    private val setAutoWallpaperUseCase: SetAutoWallpaperUseCase<br>) : ViewModel() {<br><br>    val autoWallpaperFlow: StateFlow&lt;Boolean&gt; = <br>        getAutoWallpaperUseCase().stateIn(viewModelScope, SharingStarted.Eagerly, false)<br><br>    fun toggleAutoWallpaper(enabled: Boolean) {<br>        viewModelScope.launch {<br>            setAutoWallpaperUseCase(enabled)<br>        }<br>    }<br>}</pre><h4>Conclusion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cFKJIHTdiEZKXsuWlHuSxg.png" /></figure><blockquote><em>DataStore is a future-proof solution for handling small data with clarity, safety, and flexibility.<br>If you haven’t already, start migrating now.</em></blockquote><h3>Full GitHub Source Code</h3><p>Explore the full implementation here: <a href="https://github.com/shreyashp47/DoTrack.git"><strong>github.com/shreyashp47/DoTrack</strong></a><br>(Clean Architecture + Preferences DataStore in a production-ready setup)</p><h3>Let’s Connect!</h3><p>If you find this useful, feel free to connect on <a href="https://www.linkedin.com/in/shreyashpattewardeveloper/">LinkedIn</a> or leave feedback in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98dfe4c53505" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>