Search code examples
angulartypescriptforeachobservableangular10

Running code regardless of observables existing, but waiting for them if they do?


I have the following code:

    array1.foreach(a => {
      if (a === whatever) {
        function1.subscribe();
      }
    });
    array2.foreach(b => {
      if (b === whatever) {
        function2.subscribe();
      }
    });
    function3();

How do I make sure that function3 is always called, but if function1 and/or function2 are called, it's only called after the Observables have finished?


Solution

  • You could create an array of Observables depends on your conditions and then add another one of(true) to be sure that if no Observables added to the array, combineLatest operator works anyway. Your functions function1() and function2() must return an Observable.

    const requestsArr: Observable<any>[] = [];
    
    array1.foreach(a => {
     if(a === whatever){
      requestsArr.push( function1() );
     }
    });
    
    array2.foreach(b => {
     if(b === whatever){
      requestsArr.push( function2() );
     }
    });
    
    requestsArr.push( of(true) );
    
    combineLatest(requestsArr).subscribe( (values: any[]) => {
        ...//do something with values
        function3();
    });