RxJava Observable.create vs Observable.just (1) .flatMap
I've done a bit of RxJava, and I often find myself in the case when I need to convert some existing code result to an observable.
For example, let's say the following:
ListenableFuture<T> result = request.executeAsync();
return result;
So the easiest way to convert this to an observable is to do
ListenableFuture<T> result = request.executeAsync();
return Observable.from(result);
The point is that it executeAsync
actually executes the request when it is called. What I want is to postpone this call until it is subscribed to.
I was thinking of two ways to do this
return Observable.create { aSubscriber ->
if (!aSubscriber.unsubscribed) {
aSubscriber.onNext(request.executeAsync())
}
if (!aSubscriber.unsubscribed) {
aSubscriber.onCompleted()
}
}
and
return Observable
.just(1)
.flatMap((_) -> Observable.from(request.executeAsync()));
It seems to me that it is easier to use the flatMap parameter since I don't have to worry about the caller logic.
Is there any mistake when using flatMap
over create
? Is there a preferred Rx way to make integration easier?
thank
source to share
RxJavaGuava is a small library that converts ListenableFuture
to Observable
for you, so you are better off using this rather than a do-it-yourself solution. This allows you to write
ListenableFutureObservable.from(request.executeAsync(), Schedulers.computation())
Depending on what the request is doing, you need to choose the correct scheduler.
source to share