<?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 elham chaghansou on Medium]]></title>
        <description><![CDATA[Stories by elham chaghansou on Medium]]></description>
        <link>https://medium.com/@chaghansou?source=rss-b050cd7a2c65------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*uHzl2G3_bjpvES1p</url>
            <title>Stories by elham chaghansou on Medium</title>
            <link>https://medium.com/@chaghansou?source=rss-b050cd7a2c65------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 14:52:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chaghansou/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[Visualizing Kotlin Flows and Operators: A Real-World Application]]></title>
            <link>https://medium.com/@chaghansou/visualizing-kotlin-flows-and-operators-a-real-world-application-4c2c45164950?source=rss-b050cd7a2c65------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c2c45164950</guid>
            <dc:creator><![CDATA[elham chaghansou]]></dc:creator>
            <pubDate>Thu, 05 Dec 2024 02:21:04 GMT</pubDate>
            <atom:updated>2024-12-05T13:56:49.821Z</atom:updated>
            <content:encoded><![CDATA[<p>Kotlin Flow, part of the Kotlin Coroutines library, provides an elegant way to handle asynchronous data streams. From transforming data to managing complex emissions, its operators unlock powerful capabilities for developers. This guide explores Kotlin Flow through clear definitions, practical examples, and a real-world project to help you master its potential.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mltyc-ALiWXfiep0quGDKQ.jpeg" /><figcaption>Photo by <a href="https://pixabay.com/users/congerdesign-509903/">congerdesign</a> on <a href="https://pixabay.com/">pixabay</a></figcaption></figure><h3>1. Introduction: What is Kotlin Flow?</h3><p>Kotlin Flow is a reactive streams API that allows developers to handle asynchronous data streams in a declarative and non-blocking way. Flows can emit multiple values sequentially and are designed for processing continuous streams of data, such as real-time updates or user interactions.</p><h4><strong>Key Features of Kotlin Flow</strong></h4><ul><li><strong>Cold by default:</strong> Flows only start emitting values when collected.</li><li><strong>Backpressure handling:</strong> Flows manage emissions even when the downstream collector is slow.</li><li><strong>Rich operator library:</strong> A variety of operators for transforming, filtering, and combining data.</li></ul><p>Basic Flow Example:</p><pre>import kotlinx.coroutines.flow.*<br>import kotlinx.coroutines.runBlocking<br><br>fun simpleFlow(): Flow&lt;Int&gt; = flow {<br>    for (i in 1..5) {<br>        emit(i) // Emit values<br>    }<br>}<br><br>fun main() = runBlocking {<br>    simpleFlow().collect { value -&gt;<br>        println(&quot;Collected: $value&quot;)<br>    }<br>}</pre><p>Output:</p><pre>Collected: 1<br>Collected: 2<br>Collected: 3<br>Collected: 4<br>Collected: 5</pre><h3>2. Flow Lifecycle and Types</h3><h4>Flow Lifecycle</h4><p>A flow progresses through three main stages:</p><ol><li><strong>Upstream (Source):</strong> Where data originates.</li><li><strong>Operators:</strong> Transform or filter the data as it flows downstream.</li><li><strong>Collector:</strong> The terminal operation that consumes the processed data.</li></ol><h4>Types of Flows</h4><ul><li><strong>Cold Flows:</strong> Emissions start only when collected.</li><li><strong>Hot Flows:</strong> Emissions continue regardless of whether a collector is present (e.g., SharedFlow, StateFlow).</li></ul><h3>3. Essential Operators</h3><h4>Transforming Operators</h4><ul><li><strong>map</strong>: Transforms each emitted value.</li></ul><pre>(1..5).asFlow()<br>    .map { it * 2 }<br>    .collect { println(it) }</pre><p>Output: 2, 4, 6, 8, 10</p><ul><li><strong>onEach:</strong> Used to execute side effects on each emitted value without altering the flow. This is useful for logging, debugging, or triggering actions (e.g., UI updates).</li></ul><pre>(1..5).asFlow()<br>    .onEach { value -&gt; println(&quot;Before transform: $value&quot;) } // Log each value before transformation<br>    .map { it * 2 }<br>    .onEach { value -&gt; println(&quot;After transform: $value&quot;) } // Log each value after transformation<br>    .collect { println(&quot;Collected: $it&quot;) }</pre><p>Output:</p><pre>Before transform: 1<br>After transform: 2<br>Collected: 2<br>Before transform: 2<br>After transform: 4<br>Collected: 4<br>Before transform: 3<br>After transform: 6<br>Collected: 6<br>Before transform: 4<br>After transform: 8<br>Collected: 8<br>Before transform: 5<br>After transform: 10<br>Collected: 10</pre><ul><li><strong>flatMapConcat</strong>: Maps a value to another flow and flattens sequentially.</li></ul><pre>(1..3).asFlow()<br>    .flatMapConcat { value -&gt; flowOf(&quot;$value: A&quot;, &quot;$value: B&quot;) }<br>    .collect { println(it) }</pre><p>Output:</p><pre>1: A<br>1: B<br>2: A<br>2: B<br>3: A<br>3: B</pre><h3>Filtering Operators</h3><ul><li><strong>filter</strong>: Emits values that satisfy a condition.</li></ul><pre>(1..5).asFlow()<br>    .filter { it % 2 == 0 }<br>    .collect { println(it) }</pre><p>Output: 2, 4</p><ul><li><strong>takeWhile</strong>: Emits values until a condition becomes false.</li></ul><pre>(1..5).asFlow()<br>    .takeWhile { it &lt; 4 }<br>    .collect { println(it) }</pre><p>Output: 1, 2, 3</p><h3>4. Real-World Project: Weather Dashboard</h3><h3>Objective</h3><p>Create a real-time weather dashboard that displays updates for multiple cities.</p><h4>Steps</h4><ol><li><strong>Define the Data Source</strong> Use a Flow to emit weather updates for a list of cities.</li><li><strong>Process Updates Using Operators</strong> Filter and transform the data using map, filter, and combine.</li><li><strong>Display in a Dashboard</strong> Build a simple CLI or UI with Jetpack Compose.</li></ol><h4>Code Implementation</h4><h4>Weather Data Simulation:</h4><pre>import kotlinx.coroutines.flow.*<br>import kotlinx.coroutines.runBlocking<br>import kotlinx.coroutines.delay<br><br>data class CityWeather(val city: String, val temperature: Int)<br><br>fun fetchWeatherUpdates(): Flow&lt;CityWeather&gt; = flow {<br>    val cities = listOf(&quot;New York&quot;, &quot;London&quot;, &quot;Tokyo&quot;)<br>    while (true) {<br>        for (city in cities) {<br>            emit(CityWeather(city, (0..30).random()))<br>        }<br>        delay(1000L) // Simulate real-time updates<br>    }<br>}</pre><p>Filter and Transform Data:</p><pre>fun main() = runBlocking {<br>    fetchWeatherUpdates()<br>        .onEach { println(&quot;Received weather update: ${it.city} -&gt; ${it.temperature}°C&quot;) } // Log each update<br>        .filter { it.temperature &gt; 20 } // Only show warm cities<br>        .onEach { println(&quot;Filtered warm city: ${it.city} -&gt; ${it.temperature}°C&quot;) } // Log filtered updates<br>        .map { &quot;${it.city}: ${it.temperature}°C&quot; } // Format the output<br>        .collect { println(&quot;Displaying: $it&quot;) } // Display the final data<br>}</pre><p>Example Output:</p><pre>Received weather update: New York -&gt; 22°C<br>Filtered warm city: New York -&gt; 22°C<br>Displaying: New York: 22°C<br>Received weather update: London -&gt; 15°C<br>Received weather update: Tokyo -&gt; 28°C<br>Filtered warm city: Tokyo -&gt; 28°C<br>Displaying: Tokyo: 28°C</pre><h4>Key Takeaways</h4><ul><li><strong>onEach</strong> allows for logging and side effects without altering the flow data. Here, it was used to log updates and filtered values.</li><li>The flow model ensures asynchronous and non-blocking operations, perfect for real-time applications.</li></ul><h4>Combine Multiple Flows:</h4><p>Combine weather data with another flow, such as alert notifications.</p><pre>fun alertsFlow(): Flow&lt;String&gt; = flow {<br>    val alerts = listOf(&quot;Heavy Rain&quot;, &quot;Storm Warning&quot;)<br>    for (alert in alerts) {<br>        emit(alert)<br>        delay(3000L)<br>    }<br>}<br><br>fun main() = runBlocking {<br>    fetchWeatherUpdates()<br>        .combine(alertsFlow()) { weather, alert -&gt;<br>            &quot;${weather.city}: ${weather.temperature}°C, Alert: $alert&quot;<br>        }<br>        .collect { println(it) }<br>}</pre><h3>5. Advanced Concepts: Error Handling</h3><p>Use operators like catch and retry to gracefully handle errors.</p><pre>fun fetchCityData(city: String): Flow&lt;String&gt; = flow {<br>    if (city == &quot;ErrorCity&quot;) throw Exception(&quot;Failed to fetch data&quot;)<br>    emit(&quot;$city: Data fetched successfully&quot;)<br>}<br><br>fun main() = runBlocking {<br>    listOf(&quot;New York&quot;, &quot;ErrorCity&quot;, &quot;Paris&quot;).asFlow()<br>        .flatMapConcat { fetchCityData(it) }<br>        .catch { e -&gt; emit(&quot;Error: ${e.message}&quot;) }<br>        .collect { println(it) }<br>}</pre><p>Output:</p><pre>New York: Data fetched successfully<br>Error: Failed to fetch data<br>Paris: Data fetched successfully</pre><h3>6. Conclusion</h3><p>In this guide, we explored Kotlin Flow with clear definitions, practical examples, and a complete real-world project. With its extensive library of operators and seamless integration with Kotlin Coroutines, Kotlin Flow is a robust tool for managing asynchronous data streams.</p><p>Thank you for reading this article, please give me your feedback in the comments and Clap if the article was helpful for you.</p><p>If you liked this article please follow me on Medium for more interesting articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c2c45164950" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>