<?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 Ashish Bulchandani on Medium]]></title>
        <description><![CDATA[Stories by Ashish Bulchandani on Medium]]></description>
        <link>https://medium.com/@ashishbulchandani?source=rss-1fa8e07a6cb8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*iwHYwWpuqcVqpQNu.</url>
            <title>Stories by Ashish Bulchandani on Medium</title>
            <link>https://medium.com/@ashishbulchandani?source=rss-1fa8e07a6cb8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 19:27:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashishbulchandani/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[Flow in kotlin ? Why ?]]></title>
            <link>https://medium.com/@ashishbulchandani/flow-in-kotlin-why-ec21c14b1015?source=rss-1fa8e07a6cb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec21c14b1015</guid>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-15]]></category>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[jetpack]]></category>
            <dc:creator><![CDATA[Ashish Bulchandani]]></dc:creator>
            <pubDate>Mon, 17 Feb 2025 19:50:36 GMT</pubDate>
            <atom:updated>2025-02-18T00:49:19.547Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flow in kotlin ? Why ?</h3><ul><li>Flow is a Kotlin concept that represents a stream of data which can be produced and consumed asynchronously using coroutines, essentially allowing you to handle sequences of values emitted over time without blocking the main thread, making it ideal for managing asynchronous operations like network requests or database queries within your app.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8KvqPMni1zDooptr.png" /></figure><h3>An example use case : Real-Time Stock Price Analysis Pipeline</h3><p><strong>Scenario</strong>:<br>We want to create a financial app that needs to process real-time stock prices, apply transformations (e.g., moving averages), filter anomalies, and store results in a database — <strong>all in the background</strong>, even if the UI is inactive.</p><p>Lets see how can we achieve this using flows :</p><h3>Implementation with Flows</h3><h4>1. Continuous Data Stream</h4><p>Lets assume we have an api that returns us stock price at that very moment. Here we create a flow that will wait half second and make an api call. Lets simulate a stock price API emitting prices every 500ms:</p><pre>fun fetchStockPrices(symbol: String): Flow&lt;Double&gt; = flow {<br>    while (true) { // Infinite stream<br>        delay(500)<br>        val price = api.fetchPrice(symbol) // Suspending API call<br>        emit(price)<br>    }<br>}.flowOn(Dispatchers.IO) // Offload to background thread</pre><h4>2. Complex Data Transformations</h4><p>Lets now Calculate a 10-second moving average:</p><pre>fun analyzePrices(symbol: String): Flow&lt;Double&gt; = <br>    fetchStockPrices(symbol)<br>        .buffer(50) // Handle backpressure from slow processing<br>        .runningReduce { acc, price -&gt; (acc + price) / 2 } // Moving average<br>        .map { average -&gt; round(average * 100) / 100 } // Round to 2 decimals<br>        .catch { e -&gt; logError(e) } // Handle errors</pre><h4>3. Asynchronous Database Storage</h4><p>Lets add a use case where we need to store processed data without blocking the stream:</p><pre>fun saveToDatabase(): Flow&lt;Unit&gt; = <br>    analyzePrices(&quot;GOOGL&quot;)<br>        .map { average -&gt;<br>            withContext(Dispatchers.IO) { // Async DB write<br>                database.insertStockAverage(&quot;GOOGL&quot;, average)<br>            }<br>        }</pre><h4>4. Lifecycle-Independent Processing</h4><p>We finally Launch in a CoroutineScope tied to app lifecycle (not UI):</p><pre>// In a background service or repository:<br>val analyticsScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)</pre><pre>fun startPipeline() {<br>    analyticsScope.launch {<br>        saveToDatabase()<br>            .collect() // Start the pipeline<br>    }<br>}</pre><h3>Why Flows Excel Here</h3><h4><strong>1. Continuous Stream Handling</strong></h4><ul><li>Infinite data stream (stock prices) is managed efficiently with buffer and flowOn.</li><li>No UI dependency — works even if the app is in the background.</li></ul><h4><strong>2. Complex Async Operations</strong></h4><ul><li>Mix suspending API calls (api.fetchPrice), CPU-bound math (runningReduce), and I/O (database.insert).</li><li>Operators like map and catch simplify error-prone logic.</li></ul><h4><strong>3. Backpressure Management</strong></h4><ul><li>buffer(50) ensures the producer isn’t blocked if database writes are slow.</li><li>Use conflate() if only the latest average matters during high frequency.</li></ul><h4><strong>4. Lifecycle Safety</strong></h4><ul><li>Uses a custom CoroutineScope (not tied to UI components like viewModelScope).</li><li>Survives configuration changes (e.g., screen rotation).</li></ul><h3>Lets now compare our Alternatives to flow :</h3><ul><li><strong>LiveData</strong>:<br>❌ Not designed for infinite streams.<br>❌ Lacks operators like buffer or runningReduce.<br>✅ Only use for UI updates (e.g., display final averages).</li><li><strong>RxJava</strong>:</li><li><strong>RxJava</strong>:<br>✅ Can handle this, but Kotlin Flow<br>❌ Has better Coroutines integration.<br>❌ Uses simpler Kotlin-native syntax.</li><li><strong>WorkManager</strong>:<br>❌ Built for periodic tasks, not real-time streams.</li></ul><h3>Conclusion</h3><p>In minutes we could build a very strong pipeline that :</p><ol><li>Continuously fetches prices.</li><li>Calculates moving averages.</li><li>Stores results in the database.</li><li>Runs indefinitely in the background.</li></ol><p><strong>No data loss</strong>, <strong>no UI coupling</strong>, and <strong>efficient resource usage</strong> — classic Flow strengths!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec21c14b1015" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>