RxJava - When to use Observable with create method

Viewed 5369

I was reading a tutorial:

http://code.tutsplus.com/tutorials/getting-started-with-reactivex-on-android--cms-24387

which concers RxAndroid in particular but it's pretty much the same as in RxJava. I am not sure that I understood the concept completely.

Below I have written a method and then a sample usage.

My question is: is this the right way to implement my functions so that I can run them on other threads asynchronously? They will in fact only return a created Observable running the real code, and handling errors and all that stuff.

Or is this wrong, then I'd like to know the correct way.

Observable<String> googleSomething(String text){
    return Observable.create(new Observable(){
        @Override
        public void call(Subscriber<? super String> subscriber) {
             try {
                String data = fetchData(text); // some normal method
                subscriber.onNext(data); // Emit the contents of the URL
                subscriber.onCompleted(); // Nothing more to emit
            } catch(Exception e) {
                subscriber.onError(e); // In case there are network errors
            }
        }
    });
}

googleSomething("hello world").subscribeOn(Schedulers.io()).observeOn(Schedulers.immediate()).subscribe(...)

Also is Schedulers.immediate() used in order to execute the subscriber code on the current thread? It says "Creates and returns a Scheduler that executes work immediately on the current thread." in javadoc, but I'm not sure.

4 Answers
Related