Creating Observable RxJava

Kumar Pallav
Kumar Pallav
I am a passionate java programmer, Open Source and Microservices lover, blogger and online instructor. I create Simple Short Tutorials

Creating Observable RxJava

• Kumar Pallav

Observable being the most important block of reactive programming , it is important to understand different methods of creating Observable.

Observable can be created be created by following methods.

  1. just
  2. create
  3. defer
  4. range
  5. interval
  6. repeat
  7. timer
  8. from
    • fromCallable
    • fromIterable
    • fromArray
    • fromPublisher
  • Observables emits events on which Observer subscribes too. So let us start by creating a DemoObserver which will be subscribing to our Observables.

    The above DemoObserver will be subscribing to our Observable. This will let the code be more clear and understandable. The DemoObservable is simple and logs events as subscription , errors and completion. It also adds logs each element the observable emits with onNext method.

    Let’s look at the methods of creating an Observable.

    just

    just is used to create Observable with maximum of 10 elements.  It comes handy when we have events limited to maximum of 10 events.

    The above code will create an Observable with list of alphabets from a to j . Below is the logs which will be published.

    08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onSubscribe
    08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -> a
    08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -> b
    08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -> c
    08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -> d
    08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -> e
    08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -> f
    08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -> g
    08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -> h
    08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -> i
    08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -> j
    08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onComplete

     

    The above log confirms onSubscribe , followed by onNext with elements from “a” to “j” and completed by an onComplete.

     

    The  above code can also be written using our own DemoObserver in a simple and cleaner way.

    Observable.just("a","b","c","d","e","f","g","h","i","j")
            .subscribe(new DemoObserver());

    For further example we’ll be using our DemoObserver for readability.

    In next post we will see creating observables with other methods.