Check if object is an Observable
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
.