January 11, 2019

#RxJava Part 3 : from(), just(), range(), interval(), timer()

Observable.from() Example
In the below example, the from() method dissolves the list/array and emits each value one at a time.

GIT URL: RxJavaDemoFrom.java
Observable.just()
The Observable.just() will emit whatever is present inside the just function. It can take between 2 to 9 parameters, we can pass a List/Array in it and it’ll emit the List/Array only.

GIT URL: RxJavaDemoJust.java

Observable.range()
Observable.range(start,n) methiod is used to emit 'n' number of values starting from and inclusive of start. e.g:

Observable rangeObservable = Observable.range(3,5);
rangeObservable.subscribe(intSubscriber); //emits 3,4,5,6,7
Observable.empty() //creates an empty observable that emits nothing. It just completes.
Observable.error() //creates an error. The onError() of all the subscribers would be called.
Observable.never() //does nothing. Neither emits a complete nor an error.

Observable.interval()
Observable.interval() emits constant sequences of integers in ascending order which are evenly spaced by the interval specified. e.g: Below code will emit 0 to 4 each second. We’ve set the thread to sleep to prevent the main function from returning immediately.

Observable intervalObservable = Observable.interval(1, TimeUnit.SECONDS);
intervalObservable.subscribe(System.out::println);
Thread.sleep(5000);

Observable.timer()
Unlike interval, an Observable.timer() emits value only after a certain time/delay. e.g: below code will emit only a single value after the delay.

Observable intervalObservable = Observable.timer(2, TimeUnit.SECONDS);
intervalObservable.subscribe(System.out::println);
Thread.sleep(5000);

Observable.defer()
The Observable.defer() is similar to create() except that it postpones the actual creation until an Observer subscribes. Each subscription would recall the Observable creation. This ensures that the Observer would always receive the latest data. It also ensures that no API call occurs until Subscription. The data would be only fetched when required by the observer. e.g:

Observable deferObservable = Observable.defer(() -> Observable.just(1, 2, 3));

-K Himaanshu Shuklaa..

No comments:

Post a Comment