Skip to content
This repository has been archived by the owner on Oct 22, 2021. It is now read-only.

ObservableBuilder

Ean Lombardo edited this page Jun 2, 2016 · 4 revisions

Javadoc

Want an Observable that emits "Hi", then "Hola", then does nothing for a second, then prints out "Hello!!" in System.out, then emits "words" rests for 2 more seconds then completes. I don't either but it would be easy to do with ObservableBuilder

new ObservableBuilder<String>()
                .emit("Hi")
                .emit("Hola")
                .sleep(1000)
                .perform(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("Hello!!");
                    }
                })
                .emit("words")
                .sleep(2000)
                .complete();

If you didn't have ObservableBuilder you would have to do this

Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                subscriber.onNext("Hi");
                subscriber.onNext("Hola");
                
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    subscriber.onError(e);
                }

                System.out.println("Hello!!");
                
                subscriber.onNext("words");

                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    subscriber.onError(e);
                }
                
                subscriber.onCompleted();
            }
        });

When you need an Observable that does a specific set of things, for testing or exploratory coding. ObservableBuilder makes it easier.

Calling complete(), error(), or build() will create the observable with the events you defined. If you want to build an Observable that does not fit the RX Observable contract you can use UnsafeObservableBuilder

UnsafeObservableBuilder - Javadoc

UnsafeObservableBuilder is just like an ObservableBuilder except you can call complete() and error() multiple times, and must call build() to build the final Observable

Clone this wiki locally