<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Reactive Programming Archives - Codersee blog- Kotlin on the backend</title>
	<atom:link href="https://blog.codersee.com/tag/reactive-programming/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>Kotlin &#38; Backend Tutorials - Learn Through Practice.</description>
	<lastBuildDate>Thu, 15 Feb 2024 05:00:00 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://blog.codersee.com/wp-content/uploads/2025/04/cropped-codersee_logo_circle_2-32x32.png</url>
	<title>Reactive Programming Archives - Codersee blog- Kotlin on the backend</title>
	<link></link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Reactive Programming in Kotlin: A Step-by-Step Guide</title>
		<link>https://blog.codersee.com/reactive-programming-in-kotlin-a-step-by-step-guide/</link>
					<comments>https://blog.codersee.com/reactive-programming-in-kotlin-a-step-by-step-guide/#respond</comments>
		
		<dc:creator><![CDATA[Peter Lantukh]]></dc:creator>
		<pubDate>Thu, 15 Feb 2024 05:00:00 +0000</pubDate>
				<category><![CDATA[Kotlin]]></category>
		<category><![CDATA[Coroutines]]></category>
		<category><![CDATA[Reactive Programming]]></category>
		<guid isPermaLink="false">https://codersee.com/?p=9508665</guid>

					<description><![CDATA[<p>This article provides a general overview of Reactive Programming and tools available in Kotlin in terms of Reactive Programming.</p>
<p>The post <a href="https://blog.codersee.com/reactive-programming-in-kotlin-a-step-by-step-guide/">Reactive Programming in Kotlin: A Step-by-Step Guide</a> appeared first on <a href="https://blog.codersee.com">Codersee blog- Kotlin on the backend</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this article, we are going to tackle <strong>Reactive Programming in Kotlin</strong>. We will start with what exactly <strong>Reactive Programming</strong> is, how we could use it to our advantage, and what techniques we can use in <strong>Kotlin</strong>. I am going to explain everything in simple terms to make this article <strong>beginner-friendly</strong> (considering you know the basics of Kotlin, of course).</p>



<p>In some <strong>future articles</strong>, we will put that knowledge into action on the <strong>example of the Ktor project</strong>, emphasizing the Reactive approach. So don&#8217;t forget to follow me on <a href="https://www.linkedin.com/in/peter-lantukh/" target="_blank" rel="noreferrer noopener">LinkedIn</a> to not miss out 🙂  </p>



<h2 class="wp-block-heading" id="h-reactive-programming">Reactive Programming</h2>



<p>If you try to search for what <strong>Reactive Programming</strong> is, you will sooner or later find The <strong><a href="https://www.reactivemanifesto.org/" target="_blank" rel="noreferrer noopener">Reactive Manifesto,</a></strong> which is cited by almost everyone. </p>



<p>And in most articles, there will be something like the following diagram:</p>



<figure class="wp-block-image aligncenter size-full"><img fetchpriority="high" decoding="async" width="501" height="281" src="http://blog.codersee.com/wp-content/uploads/2024/02/ReactiveApproach-1.png" alt="Image presents reactive programming diagram about manifesto: responsive, elastic, resilient, message driven. " class="wp-image-9508673" srcset="https://blog.codersee.com/wp-content/uploads/2024/02/ReactiveApproach-1.png 501w, https://blog.codersee.com/wp-content/uploads/2024/02/ReactiveApproach-1-300x168.png 300w" sizes="(max-width: 501px) 100vw, 501px" /></figure>



<p>For the beginner, all of these definitions and explanations are <strong>vague and unclear</strong>. It is absolutely possible to learn it and speak about it, for example, in an interview with zero understanding whatsoever. Instead, <strong>let&#8217;s connect it to concepts that are present in software development</strong>, and don&#8217;t worry if you are not familiar with them. </p>



<p>Let&#8217;s take a look at another diagram that represents the concepts:</p>



<figure class="wp-block-image aligncenter size-full"><img decoding="async" width="401" height="181" src="http://blog.codersee.com/wp-content/uploads/2024/02/ReactiveApproach2-1.png" alt="Image presents diagram with observer and interator pattern." class="wp-image-9508674" srcset="https://blog.codersee.com/wp-content/uploads/2024/02/ReactiveApproach2-1.png 401w, https://blog.codersee.com/wp-content/uploads/2024/02/ReactiveApproach2-1-300x135.png 300w" sizes="(max-width: 401px) 100vw, 401px" /></figure>



<p>The key concepts in the <strong>Observer Pattern</strong> are &#8220;<strong>subjects</strong>&#8221; and &#8220;<strong>observers</strong>&#8220;. When a subject&#8217;s <strong>state changes</strong>, it <strong>notifies</strong> all its observers, allowing them to react accordingly.</p>



<p>The <strong>Iterator Pattern</strong> introduces a way to access elements of some object, most likely a collection, sequentially without exposing its internal implementation.</p>



<p>And as a cherry on top, Reactive Programming is tight with <strong>Functional Programming</strong> so, in essence, let&#8217;s define what Reactive Programming is in these terms. Reactive Programming leverages the <strong>Observer&#8217;s one-to-many notification</strong> and the <strong>Iterator&#8217;s sequential access</strong>, but extends them to handle continuous data flows and <strong>asynchronous interactions</strong> without defining &#8220;what&#8221; to do with data but &#8220;how&#8221; to iterate.</p>



<h2 class="wp-block-heading" id="h-streams">Streams</h2>



<p>All mentioned before leads us to another core concept: <strong>Streams</strong>. If you are familiar with the Flows, it is basically them, if not we&#8217;ll cover them later anyway. So, a Stream is a <strong>sequence of data objects</strong> that can be consumed and processed asynchronously. What is more, you can also merge, filter, combine, and transform them to handle data successfully.</p>



<p>Now let&#8217;s check what Kotlin can offer in terms of the Reactive Approach. We will start with asynchronicity, and the best solution for this is Coroutines and especially Flows. But before that, let&#8217;s discuss types of streams.</p>



<h2 class="wp-block-heading" id="h-cold-and-hot-streams">&#8220;Cold&#8221; and &#8220;Hot&#8221; Streams</h2>



<p>In terms of emitting data, we have <strong>two types of streams</strong>. On the one hand, &#8220;<strong>cold</strong>&#8221; streams are streams that can only emit data when there is someone who could consume it, in other words, if there is any <strong>observer attached</strong>. This basically means that no data would be missed and the whole chain of the items consumed. </p>



<p>On the other hand, we have &#8220;<strong>hot</strong>&#8221; streams. They are <strong>not dependent on any observable</strong> attached and start emitting items as soon as they are created. And here is the key difference, you could &#8220;<strong>miss</strong>&#8221; values using &#8220;hot&#8221; streams if they are not handled carefully. </p>



<h2 class="wp-block-heading" id="h-kotlin-coroutines">Kotlin Coroutines </h2>



<p>Quick dive into Coroutines basics, and then we will, Coroutines allow us to create an <strong>asynchronous code execution</strong> just like threads, but they are <strong>not bound to any particular thread</strong> and without callbacks.</p>



<p>Now for the real part, the Reactive Programming Coroutines library can offer 3 options: </p>



<ul class="wp-block-list">
<li>Channels</li>



<li>StateFlow</li>



<li>SharedFlow</li>
</ul>



<p>Both StateFlow and SharedFlow are evolutions of the <strong>Flow</strong> which is generally a Stream I&#8217;ve mentioned before. Flow represents a <strong>sequence of values that can be computed asynchronously</strong>. But firstly, let&#8217;s start from Channels.</p>



<h2 class="wp-block-heading" id="h-channels">Channels</h2>



<p>The first notable object is <strong>Chanel</strong>. As documentation states, Chanel provides communication between coroutines. But in terms of our topic, Chanel is a &#8220;hot&#8221; Stream in which <strong>each individual value could consume only one observer</strong>. </p>



<p>Nevertheless, it can have more the one observer, but the values would be delivered to the first awaited. If there are many observers that wait for the value to be delivered, some collectors will get suspended. Now let&#8217;s check a simple code example: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

suspend fun fetchStockPrice(): Double {
    delay(1000) // Simulate API call delay
    return Math.random() * 100
}

fun main() = runBlocking {
    // Create a Chanel to hold stock prices
    val stockPrices = Channel&lt;Double>()

    // Launch a coroutine to fetch prices every second
    launch {
        while (isActive) {
            val price = fetchStockPrice()
            stockPrices.send(price)
            delay(1000)
        }
    }

    // Launch a coroutine to consume and display prices
    launch {
        for (price in stockPrices) {
            println("Current Stock Price: $$price")
        }
    }

    delay(Long.MAX_VALUE)
}</pre>



<p>This example simulates a stock price ticker application that fetches prices from an API in real time and displays them to the user. </p>



<p>We used Channel to handle the asynchronous data flow and transfer data from one Coroutine to another!</p>



<h2 class="wp-block-heading" id="h-sharedflow">SharedFlow</h2>



<p>The SharedFlow is a Stream in all of its glory. </p>



<p>It is a <strong>hot</strong> stream, that can have <strong>multiple numbers of observers.</strong> We can check it out with the following code example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

data class Item(val name: String, val price: Double)

fun main() = runBlocking {
    // SharedFlow to hold the cart items
    val cartItems = MutableSharedFlow&lt;List&lt;Item>>()

    // Launch a coroutine to print the cart on SharedFlow
    launch {
        cartItems.collect { items ->
            println("Cart Updated: $items")
        }
    }

    // Launch another coroutine to trigger order confirmation when the cart is full
    launch {
        cartItems.filter { it.size >= 3 } // Filter for 3 or more items
            .onEach { println("Order Confirmation triggered!") }
            .launchIn(this)
    }

    // Launch a coroutine to simulate adding items to the cart
    launch {
        var updatedItems = listOf(Item("Apple", 1.50))
        cartItems.emit(updatedItems)
        delay(1000)
        updatedItems = updatedItems + Item("Milk", 2.00)
        cartItems.emit(updatedItems)
        delay(1000)
        updatedItems = updatedItems + Item("Bread", 3.00)
        cartItems.emit(updatedItems)
    }

    delay(Long.MAX_VALUE)
}</pre>



<p>In the example above, we created a shopping cart application where multiple components need to react to changes in the cart items. </p>



<p>SharedFlow provides a centralized way to share updates efficiently. And we can witness multiple observers at the same time.</p>



<h2 class="wp-block-heading" id="h-stateflow">StateFlow</h2>



<p>The StateFlow is similar to SharedFlow. However, it is a somewhat <strong>cold</strong> stream because it <strong>requires some initial value</strong> on creation, and it <strong>always holds a value</strong>. </p>



<p>This basically means that it always has a value to observe. Here&#8217;s a good example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

enum class PlayerState {
    Playing,
    Paused,
    Stopped
}

fun main() = runBlocking {
    // StateFlow to hold the current player state
    val playerState = MutableStateFlow(PlayerState.Stopped)

    // Launch a coroutine to print state based on StateFlow
    launch {
        playerState.collect { state ->
            println("Player State: $state")
        }
    }

    // Launch a coroutine to simulate user actions
    launch {
        // Play/pause/stop actions update the state
        playerState.emit(PlayerState.Playing)
        delay(2000)
        playerState.emit(PlayerState.Paused)
        delay(1000)
        playerState.emit(PlayerState.Stopped)
    }

    delay(Long.MAX_VALUE)
}</pre>



<p>For this example, we use a music player application where the current playing state needs to be tracked. StateFlow provides a single source of truth for this state, with an initial value.</p>



<h2 class="wp-block-heading" id="h-other-reactive-options-available">Other Reactive options available</h2>



<p>The most popular alternatives are <strong>ReactiveX libraries</strong>. The main competitor is RxJava for Java basically and it&#8217;s widely used especially in <strong>Android Development</strong>. Unfortunately, <strong>RxKotlin</strong> has almost zero popularity these days due to its extensive RxJava presence. </p>



<p>RxJava provides extensive tools for Reactive programming, but due to its limited integration with <strong>Kotlin Coroutines</strong>, I recommend using Coroutines but keep in mind that this powerful tool is also available.</p>



<p>There are also lots of libraries tightly connected to <strong>Spring Boot</strong>. There are <strong>Spring WebFlux, and Project Reactor.</strong> They are provided tools in applications for building reactive systems in <strong>JVM Backend Development,</strong> but not that popular in Kotlin. </p>



<h2 class="wp-block-heading" id="h-summary">Summary</h2>



<p>And that’s all for this article about Reactive Programming in Kotlin with Coroutines and Flows.</p>



<p>In the upcoming articles, we will get back to this topic and learn how to apply this knowledge with Ktor, so don’t forget to join the free newsletter to not miss it!</p>



<p>Lastly, if you would like to learn more about Flows, then you can find lots of useful information on the <a href="https://kotlinlang.org/docs/flow.html">official documentation</a> of Kotlin.</p>
<p>The post <a href="https://blog.codersee.com/reactive-programming-in-kotlin-a-step-by-step-guide/">Reactive Programming in Kotlin: A Step-by-Step Guide</a> appeared first on <a href="https://blog.codersee.com">Codersee blog- Kotlin on the backend</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.codersee.com/reactive-programming-in-kotlin-a-step-by-step-guide/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 

Served from: blog.codersee.com @ 2026-04-27 07:30:46 by W3 Total Cache
-->