8. RxJava & RxAndroid in Kotlin

Birat Rai
3 min readDec 21, 2017

--

Kotlin series has been developed keeping in mind, you are already familiar at least at beginner’s level.

This is the Eighth milestone towards our Kotlin series. Go to the seventh milestone if you haven’t done so

In this series, we will simply follow the coding challenges developed for the Android Developer Fundamentals Course, Unit 3 — Lesson7.

This will contain the same task as in Seventh milestone, but with Rx approach. ie we will replace AsyncTask, AsyncLoader the Rx way.

Reactive RxJava RxAndroid

The topics we will learn are:

  1. RxJava
  2. RxAndroid
  3. Retrofit with Rx

What is Rx/RxJava/RxAndroid?

  • Rx (Reactive Extensions):
ReactiveX is a combination of the best ideas from
the Observer pattern, the Iterator pattern, and functional programming
RxJava is a Java VM implementation of Reactive Extensions: a library for composing asynchronous and event-based programs by using observable sequences
Android specific bindings for RxJava that make writing reactive components in Android applications easy and hassle-free. More specifically, it provides a Scheduler that schedules on the main thread or any given Looper.

Adding dependencies for Rx and Retrofit?

  • Apart from adding the dependencies for Retrofit and RxJava we need to add the retrofit adapter for RxJava so that retrofit client can emit RxJava Observables.
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxjava:2.1.7'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'

What will the retrofit Service Api look like?

  • Not much of change is needed except now RetrofitClient can emit Observables instead of plain pojo.
interface RxBooksApiService {
@GET("v1/volumes?")
fun getBookByName(@Query("q") bookName: String,
@Query("maxResults") maxResult: String,
@Query("printType") printType: String)
: Observable<Books>
// Can emit observables directly
}

How to get hold of observable?

  • Since, our RetrofitClient emits Observable we can directly consume it.
val observable = apiService().getBookByName(queryString, "2", "books")
observable.subscribeOn(Schedulers.io())

How to use RxAndroid to consume the Observable?

  • It’s similar to how we normally use Observable to subscribe in kotlin.
observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe()

How to subscribe to the Observable in kotlin?

  • With the lambda expressions in Kotlin it’s super easy and clean way to subscribe and grab the data or handle the error.
observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())

.subscribe(
{ books ->
titleText.text = books.items?.get(0)?.volumeInfo?.title ?: "No Data"
authorText.text = books.items?.get(0)?.volumeInfo!!.authors?.get(0) ?: "No author"
},
{ error ->
Toast.makeText(this, error.message,Toast.LENGTH_SHORT).show()
}
)
  • If we want to follow the onNext(), onError() and onComplete() pattern of Subscriber, than we can use RxKotlin which is an extensions for RxJava
val list = listOf("Alpha", "Beta", "Gamma", "Delta", "Epsilon")

list.toObservable() // extension function for Iterables
.filter { it.length >= 5 }
.subscribeBy(
// named arguments for lambda Subscribers
onNext = { println(it) },
onError = { it.printStackTrace() },
onComplete = { println("Done!") }
)
In love with Kotlin and RxJava

Project Source code: RxJava in Kotlin

The Ninth milestone in this series.

9. Persistence Data in Kotlin

References:

  1. Rx ~ reactive.io
  2. RxJava ~ github
  3. RxAndroid ~ github
  4. RxKotlin ~ github
  5. Retrofit Adapter for Rx ~ github
  6. RxAndroid and Kotlin ~ blog
  7. Replacing AsyncTask and AsyncLoader with Rx ~ blog

--

--

Birat Rai
Birat Rai

No responses yet