Observable vs Observer: RxJava
--
For a min, don’t think about Rxjava. If, in general, I ask you what is observable, what would you say? Lets search on google
According to google:
Observable:- able to be noticed or perceived;
Observer:- a person who watches or notices something.
Can I say here, observable is something that can be observed. Or observable is a source that we can observe for something?
For what observable can be observed, it could be any data. For example, you are watching movies on your laptop, so here your computer is observable that is emitting movies, and you are the observer who is receiving that data.
Similarly, in RxJava, Observable is something that emits some data or event, and an observer is something that receives that data or event.
Note: I will be using Kotlin code examples in this post.
Let’s create a simple observable :
val observable: Observable<T> = Observable.just(item : T)
Here T could be of any type like a string, char, int, or even a list. What observable will do here is, it will emit item T. There are other ways to emit items, we will see later in this post.
How do Observable works???.
An Observable works through its onNext(), onCompleted(), and onError() calls.
At the highest level, an Observable works by passing three types of events:
- onNext(T):- used to emit item(of type T) one at a time all the way down to the observer
- onComplete():- communicates that all data has been emitted or indicates that no item will be emitted after this call.
- onError():- communicates an error
Let’s see how can we emit a string
val observable: Observable<String> = Observable.just("Hello")
Now let’s see how to receive this string using subscribe (will discuss just in few moments):
observable.subscribe { s ->
// received string s here…