Do I create an Observable from my service when I have to optionally use http Observable or a variable?

Issue

I have a service that checks and API endpoint for status data. There are situations where I do not need to to do the API call based on other local data. This check happens in a few different components in the application.

Since I want to encapsulate the logic into the service – Do I have to create a custom Observer to return the variable to the components?

My method isClosed checks some local variables and based on that returns true or does the API call.

isClosed(): Observable<boolean> {
    let o: Observable<boolean>;


    if (myCustomLogic) {
      //do some stuff...
      //this is the api call (http.get) which returns Observable<boolean>
      o = this.checkClosed();

    } else {
      //based on myCustomLogic
      //I dont need to call the api, but I am 
      //assuming i still need an observable???
      o = new Observable((observer) => {
        console.log('Custom observer');
        observer.next(true);

        return {
          unsubscribe(): void {
            //i dont what to do here
          }
        };

      });
    }
    return o;
}

Solution

Yes, you still need an observable that always emits true and completes.

This is so common use case, that there is already "shortcut" for this, named of, so basically your code can be shortened to:

import { of } from "rxjs";
// ...
isClosed(): Observable<boolean> {
    if (myCustomLogic) {
      //do some stuff...
      //this is the api call (http.get) which returns Observable<boolean>
      return this.checkClosed();
    } else {
      return of(true);
    }
}

Answered By – Zbigniew Zagórski

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published