{"id":4725,"date":"2019-02-09T10:35:00","date_gmt":"2019-02-09T08:35:00","guid":{"rendered":"https:\/\/orfium.com\/?p=4725"},"modified":"2023-04-26T14:16:09","modified_gmt":"2023-04-26T11:16:09","slug":"introduction-to-reactive-programming","status":"publish","type":"post","link":"https:\/\/www.orfium.com\/ja\/%e3%82%ab%e3%83%86%e3%82%b4%e3%83%aa%e3%83%bc%e3%81%aa%e3%81%97\/introduction-to-reactive-programming\/","title":{"rendered":"Introduction to Reactive Programming"},"content":{"rendered":"\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" src=\"http:\/\/52.91.248.125\/wp-content\/uploads\/2023\/02\/glenn-carstens-peters-npxXWgQ33ZQ-unsplash-scaled.jpg\" alt=\"\" class=\"wp-image-872\"\/><\/figure>\n\n\n\n<p><br>As programmers, many of us have to deal with handling a response data that comes from an asynchronous callback. At first, that seems to work just fine, but as the codebase gets bigger and more complicated we start wondering if there is a better way to handle that response data and surely if there is a better way to unit test it.<\/p>\n\n\n\n<p>Such a better way exists and it\u2019s called&nbsp;<strong>Reactive Programming.<\/strong><\/p>\n\n\n\n<p>In this post, we will present a brief introduction to reactive programming and examine how it can help us build more robust applications.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What is Reactive Programming<\/strong><\/h2>\n\n\n\n<p>According to&nbsp;<a href=\"https:\/\/en.wikipedia.org\/wiki\/Reactive_programming\">wikipedia<\/a>, reactive programming is a declarative programming paradigm concerned with data streams and the propagation of change.<\/p>\n\n\n\n<p>Well, that may sound a bit complicated and doesn\u2019t really help us understand what Reactive Programming really is.<\/p>\n\n\n\n<p>So in order to keep it sharp and clear, we can describe reactive programming as programming with asynchronous data streams that a consumer observes and reacts to them.<\/p>\n\n\n\n<p>For sure, this is a much easier way to perceive it. However, we should elaborate on a small but crucial detail that differentiates this type of programming; the data streams and their meaning.<\/p>\n\n\n\n<p>In a few words, streams are a sequence of events over time. That\u2019s it, so simple.<\/p>\n\n\n\n<p>For example, a stream could be a user\u2019s action to fill a form on a website. Each keypress is an event that provides us with information on what the user is typing. &nbsp;A submit button click is an event that notifies us when the user submitted his form and consequently when the stream completed.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Why Reactive Programming<\/strong><\/h2>\n\n\n\n<p>Reactive Programming has gained a lot of popularity in recent years. You probably have&nbsp;<a href=\"https:\/\/medium.com\/@kevalpatel2106\/what-is-reactive-programming-da37c1611382\">read articles<\/a>&nbsp;or&nbsp;<a href=\"https:\/\/itnext.io\/i-would-love-to-see-you-do-it-better-and-cleaner-without-reactive-programming-545face12e1a\">attended lectures<\/a>&nbsp;on conferences or local meetups about it. You may, though, still wonder why to use it and how it would help you?<\/p>\n\n\n\n<p>The basic concept of Reactive Programming is that everything can be a stream of data. An API response, a list of rows from a local database, an Enum state class, even a button click can be represented as a stream of data able to be observed by a consumer. This stream can be filtered, transformed, combined with another stream or even shared with multiple consumers. Every stream runs on its own non-blocking thread, allowing us to execute multiple code blocks simultaneously, turning part of our application into asynchronous.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>How to use Reactive Programming<\/strong><\/h2>\n\n\n\n<p><a href=\"http:\/\/reactivex.io\/\">Reactive Extensions or Rx<\/a>&nbsp;is an implementation of Reactive Programming principles following Observer pattern, Iterator pattern and Functional Programming. In this way, Rx abstracts away any concerns about threading, synchronization, thread safety or concurrent data structures.<\/p>\n\n\n\n<p>The two key components of Rx are Observables and Subscribers, or Observers. An observable is a class that emits the stream of data. A subscriber is a consumer that subscribes, receives and reacts to the data emitted by an Observable.<\/p>\n\n\n\n<p>We can think observables as event emitters, that emit three events: onNext, onComplete, onError. The common flow of an observable is to emit the data, using the onNext method, and then call the onComplete or the onError method, if an error has occurred. When an observable calls onComplete or onError, it gets terminated. Observables are grouped by hot and cold observables;&nbsp;<a href=\"https:\/\/medium.com\/@luukgruijs\/understanding-hot-vs-cold-observables-62d04cf92e03\">you can read more about it here<\/a>.<\/p>\n\n\n\n<p>A subscriber is a class that can observe these three events, by implementing these methods and then calling the subscribe method on the observable.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Rx Operators<\/strong><\/h2>\n\n\n\n<p>By this point, Rx seems quite simple and may not sounds useful enough to start using it. However, this is where the interesting part begins! The Operators. One of the most important features of Rx is Operators. An operator is a function that takes one observable as its first argument and returns another observable. An operator allows us to take an observable, transform it and change its behavior according to our needs. Using an operator we can filter, map or cache the data emitted by an observable, combine two or more observables, chain different observables, specify the scheduler on which an observer will observe an observable, create, delay, repeat or retry an observable and many more. As we can see the true power of Rx comes from its operator.&nbsp;<a href=\"http:\/\/reactivex.io\/documentation\/operators.html\">Here you can view the whole list of Rx\u2019s operators<\/a><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" src=\"http:\/\/52.91.248.125\/wp-content\/uploads\/2023\/02\/charles-456501-unsplash-1024x683-1.jpeg\" alt=\"\" class=\"wp-image-667\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Show me some code<\/strong><\/h2>\n\n\n\n<p>Let\u2019s dive into some code to discover, through a real-world example, the true power of Rx.<\/p>\n\n\n\n<p>In our example, we will borrow the paradigm of a shopping application. When the user enters his shopping cart the flow, described below, &nbsp;must be executed :<\/p>\n\n\n\n<ul>\n<li>Request to API to get user\u2019s cart items<\/li>\n\n\n\n<li>Show loading indicator<\/li>\n\n\n\n<li>Filter the items that have zero availability<\/li>\n\n\n\n<li>Show items to the user<\/li>\n\n\n\n<li>Request to API to calculate total price from filtered items<\/li>\n\n\n\n<li>Show total price to the user<\/li>\n\n\n\n<li>Hide loading indicator<\/li>\n<\/ul>\n\n\n\n<p>In the code below, we can see how we can execute that flow, with few lines of code, using Rx.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>apiManager.getCartItems()\n  .doOnSubscribe { showIndicator() }\n  .flatMap { items -&gt; Observable.fromIterable((items)) }\n  .filter { item -&gt; item.availability &gt; 0 }\n  .toList()\n  .flatMap { items -&gt;\n      showItems(items)\n      apiManager.calculateTotal(items)\n  }\n  .doAfterTerminate { hideIndicator() }\n  .subscribe({ price -&gt; showPrice(price) }, { error -&gt; showError(error) })<\/code><\/pre>\n\n\n\n<p>Looks pretty cool, isn\u2019t it? Well, now imagine creating this with the use of old school callbacks. What a nightmare would be in case any debugging would need!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Overview<\/strong><\/h2>\n\n\n\n<p>Rx is a very powerful tool that helps us write clean, robust and scalable applications plus it tends to be a must for mobile and frontend engineers. Someone may support that familiarizing with this technology may take some time. It is though undeniable that once you reach that point, there is no way back.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>How we use it<\/strong><\/h2>\n\n\n\n<p>At&nbsp;<a href=\"https:\/\/www.orfium.com\/ja\/\">ORFIUM<\/a>&nbsp;we use Rx all over our new mobile applications. Rx is a big part of our new music player, leveraging the abilities of hot observables. Using subjects we can emit the latest state of media player, allowing our views and classes to observe it and react according to its state, without the need to have a reference to the media player itself. Excited as of how helpful Rx proved to be for us and the products we develop, we decided to share our experience with the community and open source a part of our music player in Android and iOS. Stay tuned for our next posts where we \u2018ll further elaborate on it!<\/p>\n\n\n\n<p><br><meta charset=\"utf-8\">The article was written by <strong>Dimitris Konomis<\/strong>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>As programmers, many of us have to deal with handling a response data that comes from an asynchronous callback [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"_seopress_robots_primary_cat":"none","_seopress_titles_title":"","_seopress_titles_desc":"","_seopress_robots_index":"","content-type":"","footnotes":""},"categories":[2],"tags":[],"acf":[],"_links":{"self":[{"href":"https:\/\/www.orfium.com\/ja\/wp-json\/wp\/v2\/posts\/4725"}],"collection":[{"href":"https:\/\/www.orfium.com\/ja\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.orfium.com\/ja\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.orfium.com\/ja\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/www.orfium.com\/ja\/wp-json\/wp\/v2\/comments?post=4725"}],"version-history":[{"count":1,"href":"https:\/\/www.orfium.com\/ja\/wp-json\/wp\/v2\/posts\/4725\/revisions"}],"predecessor-version":[{"id":4728,"href":"https:\/\/www.orfium.com\/ja\/wp-json\/wp\/v2\/posts\/4725\/revisions\/4728"}],"wp:attachment":[{"href":"https:\/\/www.orfium.com\/ja\/wp-json\/wp\/v2\/media?parent=4725"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.orfium.com\/ja\/wp-json\/wp\/v2\/categories?post=4725"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.orfium.com\/ja\/wp-json\/wp\/v2\/tags?post=4725"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}