Rxjava interval () reset time after some event

I am making an Android application with RxJava, on one of the pages I have a button, when I click the page will be updated. And I also want to automatically update every 10 seconds if the user has not pressed a button during this period. But when the user clicks the button, I want the automatic update action to occur 10 seconds after the click. Instead of continuing your own 10 second interval. For example, on the second 0 the application performs an automatic update, then in the second 3 the user presses a button. Then auto-update should occur on the second 13, second 23, etc. I know that there is an operator interval()that emits elements at a certain interval. But there seems to be no way to "reset" the start time. Its kind of like unsubscribing and subscribing tointerval()Observable again. A piece of code will look like

Observable<Long> intervalObservable = Observable.inteval(10, TimeUnit.SECONDS)
RxView.click(refreshButton).map(ignored -> 0L)
      .merge(intervalObservable)
      .subscibe(ignore -> performRefresh());

If there is a way to “unfreeze,” intervalObservablethen I can unload it in onNext, and then combine it again. But it seems not. How can I achieve this?

+4
source share
2 answers

You can do this quite nicely with the help of the operator switchMap. Each time the button is pressed, it switches to a new subscription for the observed interval - this means that it will start again. The previous subscription is automatically discarded, so multiple intervals will not be performed.

Observable<Long> intervalObservable = Observable.interval(10, TimeUnit.SECONDS);

RxView.clicks(refreshButton)
    .switchMap(ignored -> {
        return intervalObservable
            .startWith(0L)                 // For an immediate refresh
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext(x -> performRefresh());
    })      
    .subscribe();

startWith ( ), observeOn , (, ).

: vman , , . , 10 , - , 10 .

Observable<Long> intervalObservable = Observable.interval(10, TimeUnit.SECONDS)
    .startWith(0L)  // For an immediate refresh
    .observeOn(AndroidSchedulers.mainThread())
    .doOnNext(x -> performRefresh());

Observable<Long> buttonClickedObservable = RxView.clicks(refreshButton)
    .map(e -> 0L)  // To make the compiler happy
    .switchMap(ignored -> Observable.error(new RuntimeException("button pressed")));

Observable.merge(intervalObservable, buttonClickedObservable)
    .retry()
    .subscribe();

, ( 10 ). , . retry , ( ), .

+12

, , , ?

   Subscription subscription= null;  
   Observable<Long> interval = nul;


 public void subscribe(){

    interval = Observable
            .interval(10000L, TimeUnit.MILLISECONDS);
    subscription = interval.subscribe(item -> System.out.println("doing something")); 

}

public void eventClick(){
    if(clickButtin){
        subscription.unsubscribe();
        subscribe();
    }
}
+2

All Articles