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)
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 .
There're are basically two ways: call unsubscribe() on the Subscription object returned from the subscribe() call . use an operator.
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.
Interval Method (TimeSpan) Returns an observable sequence that produces a value after each period.
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
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