Search code examples
angularjsfirebaserxjsobservableobservers

Return Observable from Function that contains subscription and another observable


I am trying to get status of printer connected to my app. Here is the function, I have in one of the page:

checkPrinterStatus() { //I want to this this function into an observable
    this.afdb.object('food/settings/printer').snapshotChanges().subscribe((res: any) => {
      const printerSettings = res.payload.val();
      if(printerSettings.isConnected) {
        timer(5000, 3000).pipe(
          switchMap(_ => this.getConnPrinterStatus()),
          distinctUntilChanged()
        ).subscribe(async res => {
          let printerStatus = res;
          return printerStatus; // I want this to be an observable
        });  
      }
    });
    
  }

So basically, I am subscribing to my firebase database which provided me a value of wheather the printer is connected/set up or not. If it is connect, I am creating a polling where I call my getConnPrinterStatus() which returns me the status every 3 second if it has changed.

Now, currently, I have this function inside one of my page but I want to turn this function into observable so that I can put this in one of the services and then subscribe to printerStatus value in every page. How can I achieve that? Any help or direction is greatly appreciated.


Solution

  • checkPrinterStatus() { //I want to this this function into an observable
      return this.afdb.object('food/settings/printer').snapshotChanges().pipe(
        switchMap(res => iif(() => res.payload.val().isConnected, timer(5000, 3000).pipe(
            switchMap(_ => this.getConnPrinterStatus()),
            distinctUntilChanged()
          )
        ))
      );
    }
    

    This function returns an observable