Skip to content

Commit

Permalink
feat(isObservable): a new method for checking to see if an object is …
Browse files Browse the repository at this point in the history
…an RxJS Observable

I've seen a lot of code that checks to see if something is an observable by doing an `typeof` or even `instanceOf` check. It's plausible that in the future these tests might break, as they're testing implementation details of the library. It is recommended that people use this `isObservable` method to see if an object is a compatible RxJS Observable.
  • Loading branch information
benlesh committed May 1, 2018
1 parent 077f530 commit edb33e5
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
26 changes: 26 additions & 0 deletions spec/util/isObservable-spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Observable, isObservable } from 'rxjs';
import { expect } from 'chai';

describe('isObservable', () => {
it('should return true for RxJS Observable', () => {
const o = new Observable<any>();
expect(isObservable(o)).to.be.true;
});

it('should return true for an observable that comes from another RxJS 5+ library', () => {
const o: any = {
lift() { /* noop */ },
subscribe() { /* noop */ },
};

expect(isObservable(o)).to.be.true;
});

it('should NOT return true for any old subscribable', () => {
const o: any = {
subscribe() { /* noop */ },
};

expect(isObservable(o)).to.be.false;
});
});
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export { Notification } from './internal/Notification';
export { pipe } from './internal/util/pipe';
export { noop } from './internal/util/noop';
export { identity } from './internal/util/identity';
export { isObservable } from './internal/util/isObservable';

/* Error types */
export { ArgumentOutOfRangeError } from './internal/util/ArgumentOutOfRangeError';
Expand Down
10 changes: 10 additions & 0 deletions src/internal/util/isObservable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Observable } from '../Observable';
import { ObservableInput } from '../types';

/**
* Tests to see if the object is an RxJS {@link Observable}
* @param obj the object to test
*/
export function isObservable<T>(obj: any): obj is Observable<T> {
return obj && obj instanceof Observable || (typeof obj.lift === 'function' && typeof obj.subscribe === 'function');
}

0 comments on commit edb33e5

Please sign in to comment.