Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

android - Why is my timer Observable never called?

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;
        }

    });

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?

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()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 is simply an Operator to help manipulate the stream of data but it doesn't subscribe to your stream of Observables.

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();
        }
    });

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.

Here's a quick link to the Hot and Cold Observables in RxJava


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...