RxJava Android Tutorials
In this series of posts i will be covering RxJava which can used in android for asynchronous work. It extends the observer pattern to support sequences of data/events and adds operators that allow you to compose sequences together declaratively while abstracting away concerns about things like low-level threading, synchronization, thread-safety and concurrent data structures.
This diagram shows how function is applied on data which is emitted by Observable.
How to Design Using RxJava
To use RxJava you create Observables (which emit data items), transform those Observables in various ways to get the precise data items that interest you (by using Observable operators), and then observe and react to these sequences of interesting items (by implementing Observers or Subscribers and then subscribing them to the resulting transformed Observables).
A subscriber can get 3 major events :
- onNext() : Called when data after some transformation comes to subscriber.
- onError() : Some error occurred while processing.
- onCompleted() : When data emission is completed.
Adding dependency to build.gradle file
RxJava can be added to android application by simply adding gradle dependency.
1 |
compile 'io.reactivex:rxjava:1.1.6' |
Since we will be using this on android so we have to add dependency of RxAndroid in gradle file.
1 |
compile 'io.reactivex:rxandroid:1.2.1' |
Final module level build.gradle should contain highlighted lines.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
apply plugin: 'com.android.application' apply plugin: 'me.tatarka.retrolambda' android { compileSdkVersion 24 buildToolsVersion "25.0.2" defaultConfig { applicationId "net.androidsrc.rxjava" minSdkVersion 15 targetSdkVersion 24 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:24.2.1' testCompile 'junit:junit:4.12' compile 'com.jakewharton:butterknife:8.4.0' annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0' //RxJava compile 'io.reactivex:rxandroid:1.2.1' compile 'io.reactivex:rxjava:1.1.6' } |
Thats all you need to add for to use RxJava in your application. Lets now explore examples .