Why has my Observable timer never rang?

On Android I wrote Observable

which should be called once after 2000ms, 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 to Observable

drop the main thread and then call continuePlayback()

on the main thread. Contextual help allowed me to place subscribeOn/observeOn

between timer

and flatMap

. It's right? What is actually going on here and what was I doing wrong?

What happens Observable

after the call? Will it stay alive or will I need to explicitly rip it off, for example? challenge OnCompleted()

?

+2


source to share


1 answer


Most Obsersables

are passive by default, and they will only return items if signed. In your example code, you are not subscribing to yours Observable

. Therefore it never starts emitting elements or in this case single elements after 2000 milliseconds.

flatMap

- it's just Operator

to help manage your data flow, but it doesn't subscribe to your flow Observables

.

Instead of using it, flatMap

you should replace it with a call 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 Action

instead of Observer

in subscribe

as I don't think you need to handle onError

in this particular case.

Observable

from timer

will complete after it has released only the item.

Keep in mind that if you are using Observables

from Fragment

or Activity

, you should always be sure that you are unsubscribe

from yours Observables

to eliminate the possibility of a memory leak.

Here is a quick link to Hot and Cold Observations in RxJava

+3


source







All Articles