Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if object is an Observable

People also ask

How do you know if an object is observable?

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.

Can I use await for observable?

To use await with Rxjs observables, we've to convert it to a promise first. To do that, we can use the firstValueFrom or lastValueFrom functions. firstValueFrom returns promise that resolves to the first value of an observable. lastValueFrom returns promise that resolves to the last value of an observable.

Is it OK to use observable any?

if you are not using any of the features of observables you might get away with it. As for it beeing good practice, probably not. My thoughts on Promises & observables is there tools for achieving different goals & not an alternative to each other.

Can promise be converted to observable?

The correct pattern to transform a promise into an observable is using defer and from operators: import { defer, from } from 'rxjs'; const observable$ = defer(() => from(myPromise())); Why we need the defer operator? Promises are eager, this means that when called they fire instantly.


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.