Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android RxJava Observable.interval() doesn't stop emitting items

I have a static field

 private static Subscription timer;

and two static methods:

public static void setTimer() {
    timer = Observable.interval(2, TimeUnit.SECONDS, Schedulers.computation())
            .doOnNext(tick -> update(tick))
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe();
}

public static void removeTimer() {
    if (timer != null && !timer.isUnsubscribed()) {
        timer.unsubscribe();
        timer = null;
    }
}

Guessing after unsubsription Observable have to stop emitting items. However it doesn't work. If function updatePrices is

private static void update(long tick) {
    Log.d(TAG, "tick");
}

Logs continue to be printed after calling removeTimer().

So the question is how to stop emitting items in my observable correctly?

Solved

The issue was in double calling of setTimer().

However I still have a question. Can anybody explain why is the old copy of timer still continues to emit items after the second call of setTimer()?

like image 273
Bashalex Avatar asked Jul 01 '16 22:07

Bashalex


People also ask

How do you stop Observable from emitting?

Use RxJS first operator The observable$ will complete if the interval emits its first value. That means, in our console, we will see only 1 log and nothing else. At point will stop emitting values. Here, first will not emit a value until interval emits a value that is equal to 10, then it will complete the observable$.

What is Disposable Rx?

RxJava 2 introduced the concept of Disposables . Disposables are streams/links/connections between Observer and Observable . They're meant to give power to the Observers to control Observables . In most cases, the Observer is a UI element, ie; Fragment , Activity , or a corresponding viewmodel of those elements.

What is Observable and observer in RxJava?

An Observable is like a speaker that emits a value. It does some work and emits some values. An Operator is like a translator which translates/modifies data from one form to another form. An Observer gets those values.

What is single observer in RxJava?

Single is an Observable that always emit only one value or throws an error. A typical use case of Single observable would be when we make a network call in Android and receive a response.


1 Answers

Maybe too late, But may it help others!

Observable.interval(TICK_MILLIS, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
                .map(v -> v * TICK_MILLIS) // use to map value to onNext func,
                .takeUntil(v -> v > MAX_TICKS) // Stop Timer here.
                .take() // You can use take to stop timer after N count
                .subscribe(this::onNext, Log::d ,this::onComplete);
like image 120
Khaled Lela Avatar answered Nov 11 '22 12:11

Khaled Lela