{"id":100,"date":"2024-02-15T05:00:00","date_gmt":"2024-02-15T05:00:00","guid":{"rendered":"https:\/\/imcodinggenius.com\/?p=100"},"modified":"2024-02-15T05:00:00","modified_gmt":"2024-02-15T05:00:00","slug":"reactive-programming-in-kotlin-a-step-by-step-guide","status":"publish","type":"post","link":"https:\/\/imcodinggenius.com\/?p=100","title":{"rendered":"Reactive Programming in Kotlin: A Step-by-Step Guide"},"content":{"rendered":"<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>\n<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\u2019t forget to follow me on <a href=\"https:\/\/www.linkedin.com\/in\/peter-lantukh\/\" target=\"_blank\" rel=\"noopener\">LinkedIn<\/a> to not miss out   <\/p>\n<h2 class=\"wp-block-heading\">Reactive Programming<\/h2>\n<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=\"noopener\">Reactive Manifesto,<\/a><\/strong> which is cited by almost everyone. <\/p>\n<p>And in most articles, there will be something like the following diagram:<\/p>\n<div class=\"wp-block-image\">\n<\/div>\n<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\u2019s connect it to concepts that are present in software development<\/strong>, and don\u2019t worry if you are not familiar with them. <\/p>\n<p>Let\u2019s take a look at another diagram that represents the concepts:<\/p>\n<div class=\"wp-block-image\">\n<\/div>\n<p>The key concepts in the <strong>Observer Pattern<\/strong> are \u201c<strong>subjects<\/strong>\u201d and \u201c<strong>observers<\/strong>\u201c. When a subject\u2019s <strong>state changes<\/strong>, it <strong>notifies<\/strong> all its observers, allowing them to react accordingly.<\/p>\n<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>\n<p>And as a cherry on top, Reactive Programming is tight with <strong>Functional Programming<\/strong> so, in essence, let\u2019s define what Reactive Programming is in these terms. Reactive Programming leverages the <strong>Observer\u2019s one-to-many notification<\/strong> and the <strong>Iterator\u2019s sequential access<\/strong>, but extends them to handle continuous data flows and <strong>asynchronous interactions<\/strong> without defining \u201cwhat\u201d to do with data but \u201chow\u201d to iterate.<\/p>\n<h2 class=\"wp-block-heading\">Streams<\/h2>\n<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\u2019ll 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>\n<p>Now let\u2019s 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\u2019s discuss types of streams.<\/p>\n<h2 class=\"wp-block-heading\">\u201cCold\u201d and \u201cHot\u201d Streams<\/h2>\n<p>In terms of emitting data, we have <strong>two types of streams<\/strong>. On the one hand, \u201c<strong>cold<\/strong>\u201d 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>\n<p>On the other hand, we have \u201c<strong>hot<\/strong>\u201d 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 \u201c<strong>miss<\/strong>\u201d values using \u201chot\u201d streams if they are not handled carefully. <\/p>\n<h2 class=\"wp-block-heading\">Kotlin Coroutines <\/h2>\n<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>\n<p>Now for the real part, the Reactive Programming Coroutines library can offer 3 options: <\/p>\n<p>Channels<\/p>\n<p>StateFlow<\/p>\n<p>SharedFlow<\/p>\n<p>Both StateFlow and SharedFlow are evolutions of the <strong>Flow<\/strong> which is generally a Stream I\u2019ve mentioned before. Flow represents a <strong>sequence of values that can be computed asynchronously<\/strong>. But firstly, let\u2019s start from Channels.<\/p>\n<h2 class=\"wp-block-heading\">Channels<\/h2>\n<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 \u201chot\u201d Stream in which <strong>each individual value could consume only one observer<\/strong>. <\/p>\n<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\u2019s check a simple code example: <\/p>\n<p>import kotlinx.coroutines.channels.Channel<br \/>\nimport kotlinx.coroutines.delay<br \/>\nimport kotlinx.coroutines.isActive<br \/>\nimport kotlinx.coroutines.launch<br \/>\nimport kotlinx.coroutines.runBlocking<\/p>\n<p>suspend fun fetchStockPrice(): Double {<br \/>\n    delay(1000) \/\/ Simulate API call delay<br \/>\n    return Math.random() * 100<br \/>\n}<\/p>\n<p>fun main() = runBlocking {<br \/>\n    \/\/ Create a Chanel to hold stock prices<br \/>\n    val stockPrices = Channel&lt;Double&gt;()<\/p>\n<p>    \/\/ Launch a coroutine to fetch prices every second<br \/>\n    launch {<br \/>\n        while (isActive) {<br \/>\n            val price = fetchStockPrice()<br \/>\n            stockPrices.send(price)<br \/>\n            delay(1000)<br \/>\n        }<br \/>\n    }<\/p>\n<p>    \/\/ Launch a coroutine to consume and display prices<br \/>\n    launch {<br \/>\n        for (price in stockPrices) {<br \/>\n            println(&#171;Current Stock Price: $$price&#187;)<br \/>\n        }<br \/>\n    }<\/p>\n<p>    delay(Long.MAX_VALUE)<br \/>\n}<\/p>\n<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>\n<p>We used Channel to handle the asynchronous data flow and transfer data from one Coroutine to another!<\/p>\n<h2 class=\"wp-block-heading\">SharedFlow<\/h2>\n<p>The SharedFlow is a Stream in all of its glory. <\/p>\n<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>\n<p>import kotlinx.coroutines.delay<br \/>\nimport kotlinx.coroutines.flow.MutableSharedFlow<br \/>\nimport kotlinx.coroutines.flow.filter<br \/>\nimport kotlinx.coroutines.flow.launchIn<br \/>\nimport kotlinx.coroutines.flow.onEach<br \/>\nimport kotlinx.coroutines.launch<br \/>\nimport kotlinx.coroutines.runBlocking<\/p>\n<p>data class Item(val name: String, val price: Double)<\/p>\n<p>fun main() = runBlocking {<br \/>\n    \/\/ SharedFlow to hold the cart items<br \/>\n    val cartItems = MutableSharedFlow&lt;List&lt;Item&gt;&gt;()<\/p>\n<p>    \/\/ Launch a coroutine to print the cart on SharedFlow<br \/>\n    launch {<br \/>\n        cartItems.collect { items -&gt;<br \/>\n            println(&#171;Cart Updated: $items&#187;)<br \/>\n        }<br \/>\n    }<\/p>\n<p>    \/\/ Launch another coroutine to trigger order confirmation when the cart is full<br \/>\n    launch {<br \/>\n        cartItems.filter { it.size &gt;= 3 } \/\/ Filter for 3 or more items<br \/>\n            .onEach { println(&#171;Order Confirmation triggered!&#187;) }<br \/>\n            .launchIn(this)<br \/>\n    }<\/p>\n<p>    \/\/ Launch a coroutine to simulate adding items to the cart<br \/>\n    launch {<br \/>\n        var updatedItems = listOf(Item(&#171;Apple&#187;, 1.50))<br \/>\n        cartItems.emit(updatedItems)<br \/>\n        delay(1000)<br \/>\n        updatedItems = updatedItems + Item(&#171;Milk&#187;, 2.00)<br \/>\n        cartItems.emit(updatedItems)<br \/>\n        delay(1000)<br \/>\n        updatedItems = updatedItems + Item(&#171;Bread&#187;, 3.00)<br \/>\n        cartItems.emit(updatedItems)<br \/>\n    }<\/p>\n<p>    delay(Long.MAX_VALUE)<br \/>\n}<\/p>\n<p>In the example above, we created a shopping cart application where multiple components need to react to changes in the cart items. <\/p>\n<p>SharedFlow provides a centralized way to share updates efficiently. And we can witness multiple observers at the same time.<\/p>\n<h2 class=\"wp-block-heading\">StateFlow<\/h2>\n<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>\n<p>This basically means that it always has a value to observe. Here\u2019s a good example:<\/p>\n<p>import kotlinx.coroutines.delay<br \/>\nimport kotlinx.coroutines.flow.*<br \/>\nimport kotlinx.coroutines.launch<br \/>\nimport kotlinx.coroutines.runBlocking<\/p>\n<p>enum class PlayerState {<br \/>\n    Playing,<br \/>\n    Paused,<br \/>\n    Stopped<br \/>\n}<\/p>\n<p>fun main() = runBlocking {<br \/>\n    \/\/ StateFlow to hold the current player state<br \/>\n    val playerState = MutableStateFlow(PlayerState.Stopped)<\/p>\n<p>    \/\/ Launch a coroutine to print state based on StateFlow<br \/>\n    launch {<br \/>\n        playerState.collect { state -&gt;<br \/>\n            println(&#171;Player State: $state&#187;)<br \/>\n        }<br \/>\n    }<\/p>\n<p>    \/\/ Launch a coroutine to simulate user actions<br \/>\n    launch {<br \/>\n        \/\/ Play\/pause\/stop actions update the state<br \/>\n        playerState.emit(PlayerState.Playing)<br \/>\n        delay(2000)<br \/>\n        playerState.emit(PlayerState.Paused)<br \/>\n        delay(1000)<br \/>\n        playerState.emit(PlayerState.Stopped)<br \/>\n    }<\/p>\n<p>    delay(Long.MAX_VALUE)<br \/>\n}<\/p>\n<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>\n<h2 class=\"wp-block-heading\">Other Reactive options available<\/h2>\n<p>The most popular alternatives are <strong>ReactiveX libraries<\/strong>. The main competitor is RxJava for Java basically and it\u2019s 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>\n<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>\n<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>\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n<p>And that\u2019s all for this article about Reactive Programming in Kotlin with Coroutines and Flows.<\/p>\n<p>In the upcoming articles, we will get back to this topic and learn how to apply this knowledge with Ktor, so don\u2019t forget to join the free newsletter to not miss it!<\/p>\n<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>\n<p>The post <a href=\"https:\/\/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:\/\/codersee.com\/\">Codersee | Kotlin, Ktor, Spring<\/a>.<\/p>","protected":false},"excerpt":{"rendered":"<p>In this article, we are going to tackle Reactive Programming in Kotlin. We will start with what exactly Reactive Programming is, how we could use it to our advantage, and what techniques we can use in Kotlin. I am going to explain everything in simple terms to make this article &#8230; <\/p>\n<div><a class=\"more-link bs-book_btn\" href=\"https:\/\/imcodinggenius.com\/?p=100\">Read More<\/a><\/div>\n","protected":false},"author":1,"featured_media":101,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-100","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-news"],"_links":{"self":[{"href":"https:\/\/imcodinggenius.com\/index.php?rest_route=\/wp\/v2\/posts\/100"}],"collection":[{"href":"https:\/\/imcodinggenius.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/imcodinggenius.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/imcodinggenius.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/imcodinggenius.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=100"}],"version-history":[{"count":0,"href":"https:\/\/imcodinggenius.com\/index.php?rest_route=\/wp\/v2\/posts\/100\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/imcodinggenius.com\/index.php?rest_route=\/wp\/v2\/media\/101"}],"wp:attachment":[{"href":"https:\/\/imcodinggenius.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=100"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/imcodinggenius.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=100"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/imcodinggenius.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=100"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}