There are several ways to create an Observable in RxJava. The most powerful way is to use the Observable.create
method. But it's also the most complicated way. So you must avoid using it, as much as possible.
If you already have a value, you can use Observable.just
to emit your value.
Observable.just("Hello World").subscribe(System.out::println);
If you want to emit a value that is not already computed, or that can take long to be computed, you can use Observable.fromCallable
to emit your next value.
Observable.fromCallable(() -> longComputation()).subscribe(System.out::println);
longComputation()
will only be called when you subscribe to your Observable
. This way, the computation will be lazy.
Observable.defer
builds an Observable
just like Observable.fromCallable
but it is used when you need to return an Observable
instead of a value. It is useful when you want to manage the errors in your call.
Observable.defer(() -> {
try {
return Observable.just(longComputation());
} catch(SpecificException e) {
return Observable.error(e);
}).subscribe(System.out::println);