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 Apr 12, 2016 · 4 revisions

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.

Clone this wiki locally