Search code examples
javascriptrxjsrxjs5

Check if object is an Observable


I am using RxJS 5 and have this method:

Queue.prototype.drain = function (obs, opts) {};

in the method, I would like to check if the user passed in an Observable for the first argument or if they omitted the Observable and just passed in an options object.

So basically I need to do something like this:

if(!Rx.Observable.isObservable(obs)){  //this method is fictitious
    opts = obs || {};
    obs = Rx.Observable.interval(1000);
}

I assume RxJS provides users with this kind of check but I cannot find the documentation that shows you how to do this type checking.

Anyone know how?


Solution

  • Since writing this answer, RxJS version 6 has been released and, in that version, an isObservable function was added to the public API. It can be imported like this:

    import { isObservable } from "rxjs";
    

    The function signature is:

    export function isObservable<T>(obj: any): obj is Observable<T> 
    

    Since it is defined with a typeguard, the compiler can help you out like this:

    const result: any = ...;
    
    if (isObservable(result)) 
    {
       result.pipe(...);   // compiler now knows it's an observable.
    }
    

    Internally, RxJS tests for an Observable using instanceof:

    if (result instanceof Observable) {
      ...
    }
    

    So you could use:

    if (!(obs instanceof Rx.Observable)) {
      opts = obs || {};
      obs = Rx.Observable.interval(1000);
    }
    

    instanceof can be used to determine whether or not an object is an Observable from the RxJS library that you happen to be using.

    To determine if the object is a foreign observable, you can look for a Symbol.observable property.

    If the property is present and is a function, you can obtain an RxJS Observable from the foreign observable by passing the value returned by calling the object's Symbol.observable property to Rx.Observable.from.