Check if the object is observable

I am using RxJS 5 and I have this method:

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

in the method, I would like to check if the user passed Observable for the first argument or if he skipped the Observable and just passed the parameters object.

In general, 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 that RxJS provides users with such a check, but I cannot find documentation that shows how to perform this type check.

Does anyone know how?

+12
source share
2 answers

After writing this answer, RxJS version 6 was released, and in this version the isObservable function was added to the public API. This can be imported like this:

 import { isObservable } from "rxjs"; 

Function Signature:

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

Since it is defined using typeguard, the compiler can help you this way:

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

Internally, RxJS tests Observable using instanceof :

 if (result instanceof Observable) { ... } 

So you can use:

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

instanceof can be used to determine if an Observable from the RxJS library that you are using.

To determine if the Symbol.observable object Symbol.observable observable, you can find the Symbol.observable property .

If the property is present and is a function, you can get the RxJS Observable from the foreign observable by passing the value returned by calling the Symbol.observable object of the Symbol.observable property.

+22
source

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

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

Although the utilities function similar to the guard type is currently defined in the official rxjs project. It seems to be still used internally because I don't see a direct export of this function to the main index at the moment.

+1
source

Source: https://habr.com/ru/post/1262244/


All Articles