Search code examples
angularexpand

Angular 2 repeat the forkJoin 5 seconds after it's completed


I would like to repeat my forkJoin method every 5 seconds. The 5 second timer should be started once the forkJoin completed and returned the result;

This is my current forkJoin:

  let getResult1 = this.myService.GetResult1(param1, param2);       // retrun Observable<Result1>
      let getResult2 = this.myService.GetResult2(param1, param3,param4);// retrun Observable<Result2>

       Observable.forkJoin(getResult1, getResult2)
            .subscribe(results => {
              this.result1 = results[0];
              this.result2 = results[1];
              .. start counting 5 seconds and then repeat this again and again
            },
            error => this.handleError(error));

Timeline i want:

Time(s): 0 - - 1 - - 2 - - 3 - - 4 - - 5 - - 6

Action: Req - Res - - - - - - - - - - - - -Req-...

Wait: | wait for 5 seconds -------> |


Solution

  • I'm not sure if this is the most elegant way. Someone with more rxjs experience may be able provide a cleaner solution, but my first thought would be to use a Subject to determine when forkJoin should be called. Then just add a timer after the forkJoin to make another request.

    // component.ts
    subject$: Subject = new Subject();
    
    ngOnInit(){
        this.subjectSubscription = this.subject$
            .flatMap(res => {
                return Observable.forkJoin(
                    this.dummy1$, // dummy observable api
                    this.dummy2$ // dummy observable api
                );
            })
            .subscribe(res => {
                // after 5 seconds, call subject.next to fire another forkJoin call
                this.timerSubscription = Observable.timer(5000).subscribe(res => {
                    this.subject$.next();
                })
    
            });
        // make initial call
        this.subject$.next();
    }
    

    Here is a demo plnkr (https://plnkr.co/edit/OaLIMxKKUqNXxcGp0HLW?p=preview) including subscription cleanup to avoid memory leaks