user5047085
user5047085

Reputation:

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?

Upvotes: 44

Views: 32502

Answers (2)

cartant
cartant

Reputation: 58430

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.

Upvotes: 76

千木郷
千木郷

Reputation: 1821

It seems that checking the key property in the object is still an approach for checking if it is observable.

Here is an example used in the Nest.js Framework.

Although, there is exactly a type guard-like util function defined in official rxjs project currently. It is still seemed to be used internally because I don't see direct export on this function into main index currently.

Upvotes: 0

Related Questions