在Android上,我写了一个可观察的,应一次历经2000毫秒被调用,但永远不会被调用。
On Android, I have written an Observable which should be called once after 2000 msec, but which is never called.
Observable.timer(2000, TimeUnit.MILLISECONDS) // wait 2000 msec
.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
.flatMap(new Func1<Long, Observable<?>>() {
@Override public Observable<?> call(Long aLong) {
continuePlayback(); // this line is never called
return null;
}
});
我想观测到等待离开主线程,然后调用continuePlayback()的主线上。上下文帮助让我把定时器和flatMap之间subscribeOn / observeOn。它是否正确?什么是真正发生在这里和我做错了什么?
I want the Observable to wait off the main thread, then call "continuePlayback()" on the main thread. Context help allowed me to place subscribeOn/observeOn between the timer and flatMap. Is this correct? What is really happening here and what did I do wrong?
什么呼叫后发生了观测。它将停留活着,还是我需要明确其摧毁不知何故,例如调用OnCompleted()?
What happens to the Observable after the call. Will it stay alive or will I need to explicitly tear it down somehow, e.g. call OnCompleted()?
最 Obsersables
默认都是被动的,如果他们订阅了他们只会散发出的物品。在您的code例如你不订阅你的观测
。因此,它从来没有真正开始后2000毫秒发射项目或在这种情况下,唯一的项目。
Most Obsersables
are passive by default and they will only emit items if they are subscribed to. In your code example you're not subscribing to your Observable
. Therefore it never actually starts emitting items or in this case the only items after 2000 milliseconds.
flatMap
是一个简单的操作
来帮助处理数据流,但它不会订阅你的流的观测量
。
flatMap
is simply an Operator
to help manipulate the stream of data but it doesn't subscribe to your stream of Observables
.
使用 flatMap
相反的,你应该通过调用订阅替换
。
Instead of using flatMap
you should replace it with a call to subscribe
.
Observable.timer(2000, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Long>() {
@Override
public void call(Long aLong) {
continuePlayback();
}
});
我用动作
代替观察
在订阅,因为我不相信你需要在这种特殊情况下处理
的onError
。
I used the Action
instead of an Observer
in the subscribe
since I don't believe you'll need to handle onError
in this particular case.
的观测
从定时
发射它的唯一项目后,将完成。
The Observable
from timer
will complete after emitting it's only item.
请记住,如果你使用观测量
从片段
或活动你应该始终确保你取消
从记忆你的观测量
来消除机会泄漏。
Keep in mind that if you're using Observables
from within a Fragment
or an Activity
you should always make sure you unsubscribe
from your Observables
to eliminate chances of memory leaks.
这里有一个快速链接冷热观测量的RxJava