Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the interval of timer after Observable.timer created?

Tags:

rx-java

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);
        });
like image 344
kyanro Avatar asked Jul 06 '15 07:07

kyanro


1 Answers

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.

like image 68
Richard Szalay Avatar answered Oct 18 '22 21:10

Richard Szalay