I want to change the interval value which returned from api.
I have tried recreate timer (and subscribe) in subscribe. but it was not work.(because it need recursive subscribe...)
so I used member for interval value. It works. but it doesn't looks like Rx style.
// default interval. it is member
int mInterval = 10;
int initialDelay = 5;
int period = 1;
Observable.timer(initialDelay, period, TimeUnit.SECONDS)
.filter(time_sec -> time_sec % mInterval == 0)
.flatMap(time_sec -> getIntervalSecFromApi())
.subscribe(new_interval_sec -> {
// do something
Log.d("timer_log", "end:do something");
// I want to recreate timer using new_interval_sec. but I have no idea...
// so I used member for interval value.
mInterval = new_interval_sec;
});
What would be the best way to do this?
Edit
I changed code to Rx style.
BehaviorSubject<Integer> timerSubject = BehaviorSubject.create(initialDelay);
timerSubject
.switchMap(interval -> Observable.timer(interval, interval, TimeUnit.SECONDS))
.flatMap(time_sec -> getIntervalSecFromApi())
.subscribe(new_interval_sec -> {
// do something
Log.d("timer_log", "end:do something:" + new_interval_sec);
timerSubject.onNext(new_interval_sec);
});
The Rx solution to this is think of your changing time intervals as their own observable. Use a subject if you need to supply the value from an external caller.
You can then map the changing values to a timer
using switchMap
, which will automatically terminate the previous timer when the next one starts.
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