N
N
Nikolai Kupstas2016-12-28 17:03:44
Angular
Nikolai Kupstas, 2016-12-28 17:03:44

How to make an asynchronous timer using rxjs?

The main idea is to make a timer that will run every n seconds after all requests have completed. Because the project is written in Angular 2, then it should be done in rxjs
Here's what I tried to do:

export interface IAsyncTimer {
  timerObservable: Observable<any>
  observables: Array<Observable<any>>
}

@Injectable()
export class AsyncTimer {
  private timers: Map<number, IAsyncTimer> = new Map<number, IAsyncTimer>();

  public addTimer(time: number,
                  func: Observable<any>) {
    let timer = this.timers.get(time);

    if (!!timer) {
      timer.observables.push(func);
    }
    else {
      let observable = Observable.interval(time)
                                 .timeInterval(),
          timer      = {
            timerObservable: observable,
            observables    : [func]
          };
      timer.timerObservable.switchMap(Observable.forkJoin.apply(Observable, timer.observables)).subscribe(() => {});
      this.timers.set(time, timer);
    }
  }
}

For example, on a page I have several components. Each of them stores the logic for obtaining data within itself. They need to be updated every certain number of seconds. I inject the service and add the request to the queue

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question