[英]RxJava's Observable.create vs Observable.just(1).flatMap
I've been doing a bit of RxJava and i often find myself in the case where I need to transform some existing code result to an observable. 我一直在做一些RxJava,我经常发现自己需要将一些现有的代码结果转换为可观察的结果。
For instance let's take the following: 例如,让我们采取以下措施:
ListenableFuture<T> result = request.executeAsync();
return result;
So the easiest way to transform this to an observable is to do 因此,将此转换为可观察的最简单方法就是这样做
ListenableFuture<T> result = request.executeAsync();
return Observable.from(result);
The thing is that executeAsync
actually executes the request when it's called. 问题是executeAsync
实际上在调用时执行请求。 What I want is to delay that call until the observable is subscribed to. 我想要的是延迟该调用直到observable订阅。
I thought of two ways of doing 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 looks to me like it's simpler to use the flatMap option as I don't have to bother with the subscriber logic. 在我看来,使用flatMap选项更简单,因为我不必费心用户逻辑。
Is there any pitfall in using flatMap
over create
? 使用flatMap
不是create
有任何陷阱吗? Is there a preferred Rx way to ease integration ? 是否有一种首选的Rx方式来简化集成?
Thanks 谢谢
You can use defer instead : 您可以使用延迟代替:
Observable.defer(() -> request.executeAsync())
.concatMap(Observable::from)
.subscribe();
RxJavaGuava is a small library which converts ListenableFuture
to Observable
for you, so you'd better use this than a "home-made" solution. RxJavaGuava是一个小型库,可以为您将ListenableFuture
转换为Observable
,因此您最好使用它而不是“自制”解决方案。 It allows you to write 它允许你写
ListenableFutureObservable.from(request.executeAsync(), Schedulers.computation())
Depending on what the request does, you'll have to pick the right scheduler. 根据请求的作用,您必须选择正确的调度程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.