Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Reactive Programming in Kotlin

You're reading from   Reactive Programming in Kotlin Design and build non-blocking, asynchronous Kotlin applications with RXKotlin, Reactor-Kotlin, Android, and Spring

Arrow left icon
Product type Paperback
Published in Dec 2017
Publisher Packt
ISBN-13 9781788473026
Length 322 pages
Edition 1st Edition
Languages
Tools
Concepts
Arrow right icon
Author (1):
Arrow left icon
Rivu Chakraborty Rivu Chakraborty
Author Profile Icon Rivu Chakraborty
Rivu Chakraborty
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. A Short Introduction to Reactive Programming FREE CHAPTER 2. Functional Programming with Kotlin and RxKotlin 3. Observables, Observers, and Subjects 4. Introduction to Backpressure and Flowables 5. Asynchronous Data Operators and Transformations 6. More on Operators and Error Handling 7. Concurrency and Parallel Processing in RxKotlin with Schedulers 8. Testing RxKotlin Applications 9. Resource Management and Extending RxKotlin 10. Introduction to Web Programming with Spring for Kotlin Developers 11. REST APIs with Spring JPA and Hibernate 12. Reactive Kotlin and Android

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 (https://github.com/ReactiveX/RxKotlin). 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 https://github.com/ReactiveX/RxKotlin.git
$ 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:

    <dependency> 
      <groupId>io.reactivex.rxjava2</groupId> 
      <artifactId>rxkotlin</artifactId> 
      <version>2.x.y</version> 
    </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(iterator.next()) // 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 of iterator 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() 
 
      subject.map({ isEven(it) }).subscribe({println
("The number is ${(if (it) "Even" else "Odd")}" )}) subject.onNext(4) subject.onNext(9) }

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.

You have been reading a chapter from
Reactive Programming in Kotlin
Published in: Dec 2017
Publisher: Packt
ISBN-13: 9781788473026
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image