Basics Of RxJava

Akash Agrawal
3 min readApr 19, 2020

So I wouldn’t go into what RxJava is, and why is it needed. I would go direct into implementation. So there are three main elements that we need to know and they are:
1. Observable : A stream that emits data

2. Observer : A listener that listens to the data emitted by the stream

3. Subject : An object that is both an Observable and an observer, that is the Subject class implements both Observable and Observer

So enough talking, “Show me some code”

Observable.just("Hello world").subscribe(
{
Log.i(TAG, "onNext$it")
},
{
Log.i(TAG, "onError$it")
},
{
Log.i(TAG, "onCompleted")
}
)

So this seems something fancy ! What does it exactly do ? 🤔

So Observable.just() creates a stream of data ( observable) which completes when data is emitted. Now what does these three log statements do, and what are the lambdas for ? 🤔

So Observable class has a subscribe method which takes three function invocations( that is something which is invoked when a particular thing is done) for onNext() , onError() and onComplete(). So let’s discuss more about this methods.

So this methods are methods of class Observer, ya the listener which we talked about in the starting.

So this is how an observer looks like !
So lets talk about the three methods in detail :-
1. onNext() -> This method is called by the observable when it emits a new item, and the observer can listen to the new item.

2. onError() -> This method is called when Observable has a problem in emitting data. Yeah problems are with everyone ! 😂

3. onComplete() -> This is method is called just after the observable calls its onNext() the last time.

So the three lambdas/ function invocations which were shared in the above code are implementations of these three functions only.

So the code above is same, RxJava being powerful provides overloads for these methods so that the code is neater

Observable.just("Hello world").subscribe(object : Observer<String>{

override fun onNext(t: String) {
Log.i(TAG, "onNext$t")
}

override fun onError(e: Throwable) {
Log.i(TAG, "onError$e")
}

override fun onComplete() {
Log.i(TAG, "onCompleted")
}

override fun onSubscribe(d: Disposable) {

}

})
}

So here just() emits data as and when this line is executed, and hence onNext() and then onComplete() is called. So Rx has these many powerful operators, and the best way to understand them is marble diagram, whose link would be available on the source code and also on ReactiveX website.

This is a marble diagram for just, so whenever just() is called , item is emitted.

So lets talk about Subjects, the third thing in the next tutorial — Basics Of RxJava 2

--

--