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?
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()?
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$.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With