ForkJoin, repeat a specific observable call until desired value is retrieved before proceed with subscription

287 Views Asked by At

I am using ngrx store selectors on start of my component to retrieve data from my storage, these data may change any time through store dispatches from web sockets.

I am using a forkJoin on start of my component to retrieve these data from the selectors and use them appropriately.

Code example

my-component.ts

public ngOnInit(): void {
   
    forkJoin([
        this.myNgrxStore.select(storeSelector1).pipe(take(1)),
        this.myNgrxStore.select(storeSelector2).pipe(take(1)),
        this.myNgrxStore.select(storeSelector3).pipe(take(1)),
    ]).subscribe(result => { 
        // proceed with data as result[0], result[1], result[2],
        // call randomMethod only if result[1] is equal to '50', 
        // else try retrieve value from the store again till it becomes
        this.randomMethod(result[0], result[1], result[2]);
    }
}

However, I want to proceed with my randomMethod in the subscription of forkJoin only when specific value is returned from storeSelector2, for example only if response of storeSelector2 is equal to '50', if it is not, add a delay of (let's say 1000ms and retry retrieve that value).

What is the best approach to achieve my scenario? (I feel that there should be more than one). Thanks in advance

1

There are 1 best solutions below

1
Ritesh Waghela On

An example using map:

const requestArray = [];
    requestArray.push(of(1));
    requestArray.push(of(2));
    requestArray.push(of(3));
    requestArray.push(of(4));

    forkJoin(requestArray).pipe(map(result => {
      if(result[1] === 2) {
        return result;
      } else {
        return [];
      }
    })).subscribe(result => {
      if(result.length) {
        // do what you want
      }