Skip to content

Commit edb33e5

Browse files
committedMay 1, 2018
feat(isObservable): a new method for checking to see if an object is 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.
1 parent 077f530 commit edb33e5

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed
 

‎spec/util/isObservable-spec.ts

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { Observable, isObservable } from 'rxjs';
2+
import { expect } from 'chai';
3+
4+
describe('isObservable', () => {
5+
it('should return true for RxJS Observable', () => {
6+
const o = new Observable<any>();
7+
expect(isObservable(o)).to.be.true;
8+
});
9+
10+
it('should return true for an observable that comes from another RxJS 5+ library', () => {
11+
const o: any = {
12+
lift() { /* noop */ },
13+
subscribe() { /* noop */ },
14+
};
15+
16+
expect(isObservable(o)).to.be.true;
17+
});
18+
19+
it('should NOT return true for any old subscribable', () => {
20+
const o: any = {
21+
subscribe() { /* noop */ },
22+
};
23+
24+
expect(isObservable(o)).to.be.false;
25+
});
26+
});

‎src/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ export { Notification } from './internal/Notification';
3030
export { pipe } from './internal/util/pipe';
3131
export { noop } from './internal/util/noop';
3232
export { identity } from './internal/util/identity';
33+
export { isObservable } from './internal/util/isObservable';
3334

3435
/* Error types */
3536
export { ArgumentOutOfRangeError } from './internal/util/ArgumentOutOfRangeError';

‎src/internal/util/isObservable.ts

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { Observable } from '../Observable';
2+
import { ObservableInput } from '../types';
3+
4+
/**
5+
* Tests to see if the object is an RxJS {@link Observable}
6+
* @param obj the object to test
7+
*/
8+
export function isObservable<T>(obj: any): obj is Observable<T> {
9+
return obj && obj instanceof Observable || (typeof obj.lift === 'function' && typeof obj.subscribe === 'function');
10+
}

0 commit comments

Comments
 (0)
Please sign in to comment.