erhardos
erhardos

Reputation: 172

Refresh interval after emitting data form another observable

I have two observables

const refreshClick$ = Observable.fromEvent(this.btn, 'click').startWith('click')
const interval$ = Observable.interval(5000, 5000)

this.subscription = interval$
  .merge(refreshClick$)
  .flatMap(() => this.grabSomeData())
  .subscribe(newState => this.setState({newState}))

Is there a way to reset interval or delay it after recieveing event from refreshClick$ observable? So after click event setState method will be executed normaly but interval will be back after additional e.g. 5s

Upvotes: 0

Views: 41

Answers (1)

Julia Passynkova
Julia Passynkova

Reputation: 17879

You can use switchMap operator. It will complete interval observable as soon as a new click come and start a new interval observable.

const refreshClick$ = Observable.fromEvent(this.btn, 
                    'click').startWith('click');
const interval$ = Observable.interval(5000);

refreshClick$.switchMap(()=>interval$)
         .subscribe(x=>console.log(x));  

Upvotes: 1

Related Questions