How to integrate RxJava into Android App with examples

rxjava-2-android-tutorial-with-examples-feature-image

In this tutorial, grokonez.com shows you way to integrate RxJava 2 into Android App, along with 3 simple examples that apply RxJava:

  • CompoundButton (Switch) updates TextView
  • Update TextView when text length in EditText changes
  • Reactive Text search

Set up Android environment

We use Android Studio (installer from https://developer.android.com/studio/) for development. It doesn’t support RxJava, so we need to add RxJava 2 library.

Add RxJava 2 dependencies

Open app/build.gradle file, add RxJava and RxBinding wrappers for UI:

Add Java 8 lambdas

We also need to add Java 8 to the configuration to use lambdas:

Simple RxJava in Android App examples

Example 1: CompoundButton (Switch) updates TextView

rxjava-android-intro-example-1

Layout:

We’re gonna make Switch as an Observable.
– Create an Observable based on Switch (CompoundButton) change events using RxBindings library:

– Subscribe with listener function, it makes textView1 change text according to whether switchButton is checked or not.

Java code:

Example 2: Update TextView when text length in EditText changes

rxjava-android-intro-example-2

Layout:

We’re gonna make Text input as an Observable.
– Create an Observable based on EditText change events using RxBindings library:

Now the EditText can be considered an emitter of string values over time.

– Subscribe with listener function, it makes textView2 say the text is “Too long!” if editText is more than 6 characters.

Java code:

Example 3: Reactive Text Search

rxjava-android-intro-example-3

Layout:

Searches fewer than 3 characters will be filtered out, and search request will be only sent once the user hasn’t typed for 500ms:

Notice that, debounce() operator will automatically switch the thread to a background. So we call .observeOn(AndroidSchedulers.mainThread()) before doing a UI operation (updateSearchResults()) in the next step.

Java code:

Source Code

RxJava-Android-Intro

By grokonez | June 2, 2019.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*