Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop interval from observable

Tags:

rx-java

I am new on rxjava, i want to execute a polling task every 2 seconds for 50 times, also it may terminate if some condition meet in the task, i am trying to use Observable.interval but i found there is no way to terminate it except for throwing exception, is there any other operator to meet my goal ? BTW this functionality work as API to provide observable object so i can not control the subscriber and termination by unscribe.

Observable.interval(timeout, interval, TimeUnit.SECONDS)
.flatmap(task - > task)
like image 778
iammini Avatar asked Sep 05 '16 02:09

iammini


People also ask

How do I cancel my RxJS interval?

unsubscribe(); Note that since interval() is asynchronous you can call unsubscribe() inside the subscribe 's callback as well. Jul 2019: Updated for RxJS 6. subscribe leads to imperative reactive code, particularly when the intent is to unsubscribe .

How do I cancel observable timer?

There're are basically two ways: call unsubscribe() on the Subscription object returned from the subscribe() call . use an operator.

How do you stop observable?

Good. Manually unsubscribe from each observable. To unsubscribe from an observable subscription, we must create a Subscription variable (timer$), assign the subscription to this variable, and then in the ngOnDestroy lifecycle hook unsubscribe the subscription.

What is observable interval?

Interval Method (TimeSpan) Returns an observable sequence that produces a value after each period.


1 Answers

I guess Observable.takeUntil(stopPredicate) or Observable.takeWhile(predicate) can help you:

Observable.interval(timeout, interval, TimeUnit.SECONDS) 
.takeWhile(val -> val < 42)

Here observable will terminate on 42th attempt

like image 86
m.ostroverkhov Avatar answered Oct 26 '22 02:10

m.ostroverkhov