Book Image

Reactive Programming in Kotlin

By : Rivu Chakraborty
Book Image

Reactive Programming in Kotlin

By: Rivu Chakraborty

Overview of this book

In today's app-driven era, when programs are asynchronous, and responsiveness is so vital, reactive programming can help you write code that's more reliable, easier to scale, and better-performing. Reactive programming is revolutionary. With this practical book, Kotlin developers will first learn how to view problems in the reactive way, and then build programs that leverage the best features of this exciting new programming paradigm. You will begin with the general concepts of Reactive programming and then gradually move on to working with asynchronous data streams. You will dive into advanced techniques such as manipulating time in data-flow, customizing operators and provider and how to use the concurrency model to control asynchronicity of code and process event handlers effectively. You will then be introduced to functional reactive programming and will learn to apply FRP in practical use cases in Kotlin. This book will also take you one step forward by introducing you to Spring 5 and Spring Boot 2 using Kotlin. By the end of the book, you will be able to build real-world applications with reactive user interfaces as well as you'll learn to implement reactive programming paradigms in Android.
Table of Contents (20 chapters)
Title Page
About the Author
About the Reviewers
Customer Feedback


Is our world just a collection of states? No. Then why do all the programming paradigms represent our world as a series of states? Can't we reflect objects that are real, moving, and continuously changing state in programming? These are the questions that have interested me ever since I first learned programming.

When I started working as an Android developer, these questions continued to plague me, but got some friends as well. Why do we need so many loops in an application? Isn't there anything to replace the iterators? Also, for Android applications, we must keep a lot of things in mind, as the processors and RAM in a mobile device are not as powerful as those in your PC. There is often an Out of Memory Exception if you do not structure your projects well. So, if we could have less iterators in our program, the UX will significantly improve, but, how do we do it? How do we replace iterators, and with what?

One fine day, I read a blog post about reactive programming and the ReactiveX Framework, (most probably by Thomas Nield, thanks to him), and it gave me a glimpse of the answers to all my questions. So, I started learning reactive programming.

I found out that the learning curve of reactive programming is very much complex, and many developers out there leave it part way through. Reactive programming is considered an advanced topic in most places. However, I continued my journey toward learning reactive programming, and as a reward for my patience and consistency, I got answers to my questions. RxJava (and all other ReactiveX libraries) represents models just like our real-time world, and, unlike states, they model behavior with moving and continuously changing states. Unlike an iterator pattern, it believes on push mechanism, which will push data/event to the subscriber/observer as it comes, making the programming a lot more easier and a lot more like the human world.

On the other hand, around 2 years ago (in December 2015), when I read a Jetbrains blog (yes, I do read a lot, and write as well) about a new language that will work in JVM, my first thought was, why a new language? So, I started exploring Kotlin, and I fell in love with it. The sole purpose of the language is making programming a lot easier. Whenever someone speaks about the benefits of Kotlin, they talk about handling null pointer exceptions so easily, but there are a lot more advantages; the list is never-ending and continues to grow.

The best thing that can happen to a programmer is combining the Kotlin and ReactiveX Frameworks; Mario Arias did this awesome job for the sake of the Developers Community and started RxKotlin on October 2013.

The only thing that RxKotlin lacks is documentation; I personally believe that the main reason behind the complex learning curve of ReactiveX libraries is a lack of documentation and, mostly, a lack of awareness. I've seen a lot of developers, even with more than 6-8 years of experience who have not heard of reactive programming; I believe this book will have a bigger role in changing this scenario. This book is also a part of my mission (also the mission of Kotlin Kolkata User Group) to spread the use and knowledge of Kotlin as much as possible.

As per as my knowledge, this is the first book that helps you learn reactive programming in Kotlin, covering RxKotlin (precisely RxKotlin 2.0) and the Reactor-Kotlin Framework. It is a step-by-step guide to learn RxKotlin and Reactor-Kotlin with added coverage on Spring and Android. I hope this book will help you find the benefits of Kotlin and reactive programming altogether, and, with the help of this book, you will be able to successfully apply reactive programming to all your Kotlin projects.

If you have any concerns, feedback, or comments, you can contact me through my site, or drop an email to [email protected]. Make sure to mention Book Query - Reactive Programming in Kotlin in the subject of the email.

What this book covers

Chapter 1, A Short Introduction to Reactive Programming, helps you understand the context, thinking pattern, and principles of reactive programming.

Chapter 2, Functional Programming with Kotlin and RxKotlin, chapter walks you through the essential concepts of functional programming paradigms and their possible implementations on Kotlin so that you can understand functional reactive programming easily.

Chapter 3, Observables, Observers, and Subjects, enables you to gain a grip on the base of RxKotlin—Observables, Observers, and Subjects lay at the core of RxKotlin.

Chapter 4, Introduction to Backpressure and Flowables, introduces you to Flowables, which enable you to use Backpressure—a technique in RxKotlin that prevents producers from outpacing consumers.

Chapter 5, Asynchronous Data Operators and Transformations, introduces you to operators in RxKotlin.

Chapter 6, More on Operators and Error Handling, gets your grip stronger on operators, and introduces how to combine producers and how to filter them with operators. This chapter will also help you handle errors more efficiently in RxKotlin.

Chapter 7, Concurrency and Parallel Processing in RxKotlin with Schedulers, enables you to leverage the benefits of Schedulers to achieve concurrent programming.

Chapter 8, Testing RxKotlin Applications, walks you through the most crucial part of application development—testing—which is a bit different in RxKotlin as reactive programming defines behaviors instead of states. This chapter starts with the basics of testing, enabling you to learn testing from scratch.

Chapter 9, Resource Management and Extending RxKotlin, helps you learn how to manage resources in Kotlin—resources could be database instances, files, HTTP accesses, or anything that needs to be closed. You will also learn how to create your own custom operators in RxKotlin in this chapter.

Chapter 10, Introduction to Web Programming with Spring for Kotlin Developers, gets you started with Spring and Hibernate so that you can leverage its benefits while writing APIs in Kotlin.

Chapter 11, REST APIs with Spring JPA and Hibernate, introduces you to the Reactor framework, the reactor-kotlin extension, so that you can apply reactive programming with Spring in Kotlin.

Chapter 12, Reactive Kotlin and Android, the last chapter of this book, gets you started with reactive programming in Android with Kotlin.

What you need for this book

We will be using Java 8 and Kotlin 1.1.50 for the programs in this book, so Oracle's JDK 1.8 along with Kotlin 1.1.50 (this can be skipped downloading if you're using IntelliJ IDEA) will be required. You will need an environment to write and compile your Kotlin code (I strongly recommend Intellij IDEA, but you can use anything of your choice), and preferably a build automation system such as Gradle or Maven. Later in this book, we will use Android Studio (2.3.3 or 3.0). Everything you need in this book should be free to use and not require commercial or personal licensing (we are using the IntelliJ IDEA Community Edition).

Who this book is for

This book is for Kotlin developers who would like to build fault-tolerant, scalable, and distributed systems. A basic knowledge of Kotlin is required; however, no prior knowledge of reactive programming is assumed.


In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Let's first take a look at the init block of the ReactiveCalculator class"

A block of code is set as follows:

   async(CommonPool) { 
        Observable.range(1, 10) 
          .subscribe { 
              runBlocking { delay(200) } 
              println("Observable1 Item Received $it") 

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

abstract class BaseActivity : AppCompatActivity() { 
       final override fun onCreate(savedInstanceState: Bundle?) { 
        abstract fun onCreateBaseActivity(savedInstanceState: Bundle?) 

Any command-line input or output is written as follows. The input command might be broken into several lines to aid readability, but needs to be entered as one continuous line in the prompt:

$ git clone$ cd RxKotlin/$ ./gradlew build

New terms and important words are shown in bold.  Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Go to Android Studio | Settings | Plugins."


Warnings or important notes appear like this.


Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.
  2. Hover the mouse pointer on the SUPPORT tab at the top.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box.
  5. Select the book for which you're looking to download the code files.
  6. Choose from the drop-down menu where you purchased this book from.
  7. Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows
  • Zipeg / iZip / UnRarX for Mac
  • 7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at We also have other code bundles from our rich catalog of books and videos available at Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from


Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to and enter the name of the book in the search field. The required information will appear under the Errata section.


Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.


If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.