Search icon CANCEL
Cart icon
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Learning Hub
Free Learning
Arrow right icon
Reactive Programming in Kotlin
Reactive Programming in Kotlin

Reactive Programming in Kotlin: Design and build non-blocking, asynchronous Kotlin applications with RXKotlin, Reactor-Kotlin, Android, and Spring

By Rivu Chakraborty
$39.99 $27.98
Book Dec 2017 322 pages 1st Edition
$39.99 $27.98
$15.99 Monthly
$39.99 $27.98
$15.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now
Table of content icon View table of contents Preview book icon Preview Book

Reactive Programming in Kotlin

Chapter 1. A Short Introduction to Reactive Programming

The term reactive got famous recently. Not only did it get trending, but it has started ruling the software development sector with new blog posts articles every day, and presentations, emerging frameworks and libraries, and more. Even the big IT companies that are often referred to as market giants, such as Google, Facebook, Amazon, Microsoft, and Netflix, are not only supporting and using reactive programming themselves, but they've even started releasing new frameworks for the same.

So, as a programmer, we are wondering about reactive programming. Why is everyone getting crazy about it? What does reactive programming exactly mean? What are the benefits of reactive programming? And, finally, should we learn it? If yes, then how?

On the other hand, Kotlin is also the newest programming language you've heard of (we're guessing you've heard of Kotlin, as this book assumes that you've a little understanding of the language). Kotlin, as a language, solves many important problems in Java. The best part is its interoperability with Java. If you carefully watch the trends, then you would know that Kotlin has created not a strong wind but a storm to blow things around it. Even the Google at Google IO/17 declared its official support for Kotlin as an official programming language for Android application development, noting that it is the first time since the perception of the Android Framework that Google has added another language to the Android family other than Java. Soon after, Spring also expressed their support for Kotlin.

To say it in simple words, Kotlin is powerful enough to create a great application, but if you combine reactive programming style with Kotlin, it would be super easy to build great apps better.

This book will present reactive programming in Kotlin with RxKotlin and Reactor, along with their implementations in Spring, Hibernate, and Android.

In this chapter, we will cover the following topics:

  • What is reactive programming?
  • Reasons to adapt functional reactive programming
  • Reactive Manifesto
  • Comparison between the observer (reactive) pattern and familiar patterns
  • Getting started with RxKotlin

What is reactive programming?

Reactive programming is an asynchronous programming paradigm that revolves around data streams and the propagation of change. In simpler words, those programs which propagate all the changes that affected its data/data streams to all the interested parties (such as end users, components and sub-parts, and other programs that are somehow related) are called reactive programs.

For example, take any spreadsheet (say the Google Sheet), put any number in the A1 cell, and in the B1 cell, write the =ISEVEN(A1) function; it'll show TRUEor FALSE, depending on whether you've entered an even or odd number. Now, if you modify the number in A1, the value of B1 will also get changed automatically; such behavior is called reactive.

Not clear enough? Let's look at a coding example and then try to understand it again. The following is a normal Kotlin code block to determine if a number is even or odd:

    fun main(args: Array<String>) { 
      var number = 4 
      var isEven = isEven(number) 
      println("The number is " + (if (isEven) "Even" else "Odd")) 
      number = 9 
      println("The number is " + (if (isEven) "Even" else "Odd")) 
    fun isEven(n:Int):Boolean = ((n % 2) == 0) 

If you check the output of the program, then you'll see that, although the number is assigned a new value, isEven is still true; however, if isEven was made to track changes of the number, then it would automatically become false. A reactive program would just do the same.

Reasons to adapt functional reactive programming

So, let's first discuss the reasons to adapt functional reactive programming. There's no point in changing the whole way you code unless it gets you some really significant benefits, right? Yes, functional reactive programming gets you a set of mind-blowing benefits, as listed here:

  • Get rid of the callback hell: A callback is a method that gets called when a predefined event occurs. The mechanism of passing interfaces with callback methods is called callback mechanism. This mechanism involves a hell of a lot of code, including the interfaces, their implementations, and more. Hence, it is referred to as callback hell.
  • Standard mechanism for error handling: Generally, while working with complex tasks and HTTP calls, handling errors are a major concern, especially in the absence of any standard mechanism, it becomes a headache.
  • It's a lot simpler than regular threading: Though Kotlin makes it easier to work with threading as compared to Java, it's still complicated enough. Reactive programming helps to make it easier.
  • Straightforward way for async operations: Threading and asynchronous operations are interrelated. As threading got easier, so did the async operations.
  • One for everythingthe same API for every operations: Reactive programming, especially RxKotlin, offers you a simple and straightforward API. You can use it for anything and everything, be it network call, database access, computation, or UI operations.
  • The functional way: Reactive programming leads you to write readable declarative code as, here, things are more functional.
  • Maintainable and testable code: The most important point-by following reactive programming properly, your program becomes more maintainable and testable.

Reactive Manifesto

So, what is the Reactive Manifesto? The Reactive Manifesto ( is a document defining the four reactive principles. You can think of it as the map to the treasure of reactive programming, or like the bible for the programmers of the reactive programming religion.

Everyone starting with reactive programming should have a read of the manifesto to understand what reactive programming is all about and what its principles are.

So, the following is the gist of four principles that Reactive Manifesto defines:

  • Responsive: The system responds in a timely manner. Responsive systems focus on providing rapid and consistent response times, so they deliver a consistent quality of service.
  • Resilient: In case the system faces any failure, it stays responsive. Resilience is achieved by replication, containment, isolation, and delegation. Failures are contained within each component, isolating components from each other, so when failure has occurred in a component, it will not affect the other components or the system as a whole.
  • Elastic: Reactive systems can react to changes and stay responsive under varying workload. They achieve elasticity in a cost effective way on commodity hardware and software platforms.
  • Message driven: In order to establish the resilient principle, reactive systems need to establish a boundary between components by relying on asynchronous message passing.

By implementing all four preceding principles, the system becomes reliable and responsive thus, reactive.

Reactive Streams standard specifications

Along with the Reactive Manifesto, we also have a standard specification on Reactive Streams. Everything in the reactive world is accomplished with the help of Reactive Streams. In 2013, Netflix, Pivotal, and Lightbend (previously known as Typesafe) felt a need for a standards specification for Reactive Streams as the reactive programming was beginning to spread and more frameworks for reactive programming were starting to emerge, so they started the initiative that resulted in Reactive Streams standard specification, which is now getting implemented across various frameworks and platforms.

You can take a look at the Reactive Streams standard specification at—

Reactive Frameworks for Kotlin

To write Reactive programs, we need a library or a specific programming language; we can't refer to Kotlin as a reactive language (basically, I don't know any such language that is reactive by itself) as it is a powerful and flexible programming language for modern multiplatform applications, fully interoperable with Java and Android. However, there are reactive libraries out there to help us with these. So, let's take a look at the available list:

  • RxKotlin
  • Reactor-Kotlin
  • Redux-Kotlin
  • FunKTionale
  • RxJava and other Reactive Java Frameworks can also be used with Kotlin (as Kotlin is 100% interoperable with Java-bidirectional)


In this book, we will focus on RxJava and Reactor-kotlin (in the later chapters, on Spring).

Getting started with RxKotlin

RxKotlin is a specific implementation of reactive programming for Kotlin, which is influenced by functional programming. It favors function composition, avoidance of global state, and side effects. It relies on the observer pattern of producer/consumer, with a lot of operators that allow composing, scheduling, throttling, transforming, error handling, and lifecycle management.

Whereas Reactor-Kotlin is also based on functional programming, and it is widely accepted and backed by the Spring Framework.

Downloading and setting up RxKotlin

You can download and build RxKotlin from GitHub ( I do not require any other dependencies. The documentation on the GitHub wiki page is well structured. Here's how you can check out the project from GitHub and run the build:

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

You can also use Maven and Gradle, as instructed on the page.

For Gradle, use the following compile dependency:

compile 'io.reactivex.rxjava2:rxkotlin:2.x.y'

For Maven, use this dependency:


This book targets RxKotlin 2.x, so remember to use io.reactive.rxjava2 instead of io.reactivex.rxkotlin, as the latter one is for RxKotlin 1.x.


Note that we are using RxKotlin version 2.1.0 for this book.

Now, let's take a look at what RxKotlin is all about. We will begin with something well-known and, gradually, we will get into the secrets of the library.

Comparing the pull mechanism with the RxJava push mechanism

RxKotlin revolves around the observable type that represents a system of data/events intended for push mechanism (instead of the pull mechanism of the iterator pattern of traditional programs), thus it is lazy and can be used synchronously and asynchronously.

It will be easier for us to understand if we start with a simple example that works with a list of data. So, here is the code:

    fun main(args: Array<String>) { 
      var list:List<Any> = listOf("One", 2, "Three", "Four", 4.5,
      "Five", 6.0f) // 1 
      var iterator = list.iterator() // 2 
      while (iterator.hasNext()) { // 3 
        println( // Prints each element 4 

The following screenshot is the output:

So, let's go through the program line by line to understand how it works.

At comment 1, we're creating a list of seven items (the list contains data of mixed data types with the help of any class). On comment 2, we are creating iterator from the list, so that we can iterate over the data. In comment 3, we have created a while loop to pull data from the list with the help of iterator, and then, in 4, we're printing it.

The thing to notice is that we're pulling data from the list while the current thread is blocked until the data is received and ready. For example, think of getting that data from a network call/database query instead of just List and, in that case, how long the thread will be blocked. You can obviously create a separate thread for those operations, but then also, it will increase complexity.

Just give a thought; which one is a better approach? Making the program wait for data or pushing data to the program whenever it's available?

The building blocks of the ReactiveX Framework (be it RxKotlin or RxJava) are the observables. The observable class is just the opposite ofiterator interface. It has an underlying collection or computation that produces values that can be consumed by a consumer. However, the difference is that the consumer doesn't pull these values from the producer, like in the iterator pattern; instead, the producer pushes the values as notifications to the consumer.

So, let's take the same example again, this time with observable:

    fun main(args: Array<String>) { 
      var list:List<Any> = listOf("One", 2, "Three",
      "Four", 4.5, "Five", 6.0f) // 1 
      var observable: Observable<Any> = list.toObservable(); 
       observable.subscribeBy( // named arguments for
       lambda Subscribers 
         onNext = { println(it) }, 
         onError =  { it.printStackTrace() }, 
         onComplete = { println("Done!") } 

This program output is the same as the previous one—it prints all the items in the list. The difference is in the approach. So, let's see how it actually works:

  1. Create a list (just the same as the previous one).
  2. An observable instance is created with that list.
  3. We're subscribing to the observer instance (we're using named arguments for lambda and covering it in detail later).

As we subscribe to observable, each data will be pushed to onNext, and, as it gets ready, it will call onComplete when all data is pushed and onError if any error occurs.

So, you learned to use the observable instances, and they are quite similar to the iterator instances, which is something we're very familiar with. We can use these observable instances to build asynchronous streams and push data updates to their subscribers (even to multiple subscribers).This was a simple implementation of the reactive programming paradigm. The data is being propagated to all the interested parties—the subscribers.

The ReactiveEvenOdd program

So, now that we are somewhat familiar with observables, let's modify the even-odd program in a reactive way. Here is the code for doing so:

    fun main(args: Array<String>) { 
      var subject:Subject<Int> = PublishSubject.create(){ isEven(it) }).subscribe({println
      ("The number is ${(if (it) "Even" else "Odd")}" )}) 

Here is the output:

In this program, we have used subject and map, which we will cover in the later chapters. Here, it is just to show how easy it is in reactive programming to notify the changes. If you look at the program closely, then you'll also find that the code is modular and functional. When we notify subject with a number, it calls the method in map, then it calls the method in subscribe with the return value of the map method. The map method checks if the number is even and returns true or false accordingly; in the subscribe method, we are receiving that value and printing even or odd accordingly. The subject.onNext method is the way through which we message the new value to the subject, so it can process it.

The ReactiveCalculator project

So, let's start with an event with the user input. Go through the following example:

    fun main(args: Array<String>) { 
      println("Initial Out put with a = 15, b = 10") 
      var calculator:ReactiveCalculator = ReactiveCalculator(15,10) 
      println("Enter a = <number> or b = <number> in separate
      lines\nexit to exit the program") 
      var line:String? 
      do { 
        line = readLine(); 
      } while (line!= null && !line.toLowerCase().contains("exit")) 

If you run the code, you'll get the following output:

In the main method, we are not doing much operation except for just listening to the input and passing it to the ReactiveCalculator class, and doing all other operations in the class itself, thus it is modular. In the later chapters, we will create a separate observable for the input process, and we will process all user inputs there. We have followed the pull mechanism on the user input for the sake of simplicity, which you will learn to remove in the next chapters. So, let's now take a look at the following ReactiveCalculator class:

    class ReactiveCalculator(a:Int, b:Int) { 
      internal val subjectAdd: Subject<Pair<Int,Int>> = 
      internal val subjectSub: Subject<Pair<Int,Int>> =
      internal val subjectMult: Subject<Pair<Int,Int>> =
      internal val subjectDiv: Subject<Pair<Int,Int>> =
      internal val subjectCalc:Subject<ReactiveCalculator> =
      internal var nums:Pair<Int,Int> = Pair(0,0) 
        nums = Pair(a,b) 
{ it.first+it.second }).subscribe
        ({println("Add = $it")} ){ it.first-it.second }).subscribe
        ({println("Substract = $it")} ){ it.first*it.second }).subscribe
        ({println("Multiply = $it")} ){ it.first/(it.second*1.0) }).subscribe
        ({println("Divide = $it")} ) 
          with(it) { 
        fun calculateAddition() { 
        fun calculateSubstraction() { 
        fun calculateMultiplication() { 
        fun calculateDivision() { 
        fun modifyNumbers (a:Int = nums.first, b: Int = nums.second) { 
          nums = Pair(a,b) 
       fun handleInput(inputLine:String?) { 
        if(!inputLine.equals("exit")) { 
            val pattern: Pattern = Pattern.compile
            var a: Int? = null 
            var b: Int? = null 
            val matcher: Matcher = pattern.matcher(inputLine) 
            if (matcher.matches() && != null 
            && != null) { 
                 a = 
              } else if("b")){ 
                 b = 
            when { 
              a != null && b != null -> modifyNumbers(a, b) 
              a != null -> modifyNumbers(a = a) 
              b != null -> modifyNumbers(b = b) 
              else -> println("Invalid Input") 

In this program, we have push mechanism (observable pattern) only to the data, not the event (user input). While the initial chapters in this book will show you how to observe on data changes; RxJava also allows you to observer events (such as user input), we will get them covered during the end of the book while discussing RxJava on Android. So, now, let's understand how this code works.

First, we created a ReactiveCalculator class, which observes on its data and even on itself; so, whenever its property is modified, it calls all its calculate methods.

We used Pair to pair two variables and created four subject on the Pair to observe changes on it and then process it; we need four subject as there are four separate operations. You will also learn to optimize it with just one method in the later chapters.

On the calculate methods, we are just notifying the subject to process the Pair and print the new result.

If you focus on the map methods in both the programs, then you will learn that the map method takes the value that we passed with onNext and processes it to come up with a resultant value; that resultant value can be of any data type, and this resultant value is passed to the subscriber to process further and/or show the output.


In this chapter, we learned about what reactive programming is and the reasons we should learn it. We also started with coding. The reactive coding pattern may seem new or somehow uncommon, but it is not that hard; while using it, you just need to declare a few more things.

We learned about observable and its use. We also got introduced to subject and map, which we will learn in depth in the later chapters.

We will continue with ReactiveCalculator example in the later chapters and see how we can optimize and enhance this program.

The three examples presented in this chapter may seem a bit confusing and complex at first, but they're really simple, and they will become familiar to you as you proceed with this book.

In the next chapter, we will learn more about functional programming and functional interfaces in RxKotlin.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • • Learn how to solve blocking user experience with Reactive Programming and get deep insights into RxKotlin
  • • Integrate Reactive Kotlin with Spring and build fantastic Android Apps with RxKotlin and RxAndroid
  • • Build reactive architectures that reduce complexity throughout the development process and make your apps(web and Android) scalable


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.

What you will learn

• Learn about reactive programming paradigms and how reactive programming can improve your existing projects • Gain in-depth knowledge in RxKotlin 2.0 and the ReactiveX Framework • Use RxKotlin with Android • Create your own custom operators in RxKotlin • Use Spring Framework 5.0 with Kotlin • Use the reactor-kotlin extension • Build Rest APIs with Spring, Hibernate, and RxKotlin • Use testSubscriber to test RxKotlin applications • Use backpressure management and Flowables

Product Details

Country selected

Publication date : Dec 5, 2017
Length 322 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781788473026
Vendor :
Category :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details

Publication date : Dec 5, 2017
Length 322 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781788473026
Vendor :
Category :

Table of Contents

20 Chapters
Title Page Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
About the Reviewers Chevron down icon Chevron up icon Chevron down icon Chevron up icon
Customer Feedback Chevron down icon Chevron up icon
Dedication Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
1. A Short Introduction to Reactive Programming Chevron down icon Chevron up icon
2. Functional Programming with Kotlin and RxKotlin Chevron down icon Chevron up icon
3. Observables, Observers, and Subjects Chevron down icon Chevron up icon
4. Introduction to Backpressure and Flowables Chevron down icon Chevron up icon
5. Asynchronous Data Operators and Transformations Chevron down icon Chevron up icon
6. More on Operators and Error Handling Chevron down icon Chevron up icon
7. Concurrency and Parallel Processing in RxKotlin with Schedulers Chevron down icon Chevron up icon
8. Testing RxKotlin Applications Chevron down icon Chevron up icon
9. Resource Management and Extending RxKotlin Chevron down icon Chevron up icon
10. Introduction to Web Programming with Spring for Kotlin Developers Chevron down icon Chevron up icon
11. REST APIs with Spring JPA and Hibernate Chevron down icon Chevron up icon
12. Reactive Kotlin and Android Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Top Reviews
No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial


How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to
  • To contact us directly if a problem is not resolved, use
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.