Rx Java Observable执行直到某些情况 [英] Rx Java Observable execute until some condition
问题描述
我试图找到一种在满足某些条件之前可以执行观察的方法.
I am trying to find a way to execute observable until some condition is met.
请考虑以下示例:
myDelayedObservable = createListenerObserver();
public Observable<Boolean> createListenerObserver() {
// The part I am looking for
}
ViewTreeObserver.OnGlobalLayoutListener listenerLayout = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
myDelayedObservable.onCompleted();
getTargetView().getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
};
public void performMultipleRequests() {
Observable<Boolean> longRunningTask = Observable.zip(oneRequest, anotherRequest, myDelayedObservable,...);
}
因此,想法是运行多个请求(例如下载请求)以及使用zip
的myDelayedObservable
,因此,仅当所有请求和侦听器(在我的情况下为完成的布局)完成时,longRunningTask
才完成.
So the idea is to run multiple requests, for instance a download request, together with myDelayedObservable
using zip
, so longRunningTask
completes only when all requests plus listener (in my case view finished layout) are completed.
但是问题是,我找不到为侦听器创建Observable的正确方法.就像障碍一样,伪代码
But the problem is, I cannot find the right way to create my Observable for listener. It is like a barrier, so pseudo code
while(!viewIsLaidOut) {
// just wait
}
observable.complete();
// After that `longRunningTask` should be completed
请提出实现此目标的正确方法,我已经考虑过Future
,Callable
,但这似乎并不是我的最佳解决方案.
Please suggest the right way to achieve this, I have thought about Future
, Callable
but this seems to not be the best solution to me.
推荐答案
1)您需要map
所有可观测值都具有相同的类型,例如. Observable<Boolean>
,因此您可以将它们合并:
1) You need to map
all observables to the same type, eg. Observable<Boolean>
, so you can merge them:
observable1.map(String s -> "...".equals(s))
observable2.map(Integer i -> i > 0 && i < 100)
observable3.map(MyClass m -> true)
...
2)使用Observable.merge()
将它们全部合并为单个流. 为此目的使用zip
仅在所有可观察物发出相同数量的项目时才有效,否则它将在第一个完成后立即完成,而无需等待其余的时间.
2) Use Observable.merge()
to merge them all into single stream. Using zip
for this purpose will only work if all observables emit the same number of items, otherwise it will complete as soon as the first one completes, without waiting for the rest.
Observable<Boolean> allInOne = Observable.merge(observable1, observable2, ...);
3)myDelayedObservable
只是在某些侦听器回叫之前保持allInOne
不完整的那些可观察对象之一.为此使用Subject
:
3) myDelayedObservable
is just one of those observables that shall hold allInOne
incomplete until some listener calls back. Use Subject
for this purpose:
Subject<Boolean> myDelayedObservable = PublishSubject.create();
4)听众准备就绪后,呼叫myDelayedObservable.onComplete()
.
4) When your listener is ready, call myDelayedObservable.onComplete()
.
5)订阅allInOne
并在完成时做出反应:
5) Subscribe to allInOne
and react on completion:
allInOne.subscribe(b -> { ... }, e -> { ... },
() -> { ... go ahead with your next task ... });
这篇关于Rx Java Observable执行直到某些情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!