Skip to content

Commit

Permalink
feat(core): add observe util (#2808)
Browse files Browse the repository at this point in the history
  • Loading branch information
griest024 committed May 22, 2024
1 parent 24ca71c commit 1874709
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
35 changes: 35 additions & 0 deletions libs/core/src/utils/observe.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import {
cold,
hot,
} from 'jasmine-marbles';

import { observe } from './observe';

describe('@daffodil/core | observe', () => {
describe('when the passed value is an observable', () => {
it('should return an equivalent observable', () => {
const val = 5;
expect(observe(hot('--a', { a: val }))).toBeObservable(cold('--a', { a: val }));
});
});

describe('when the passed value is a promise', () => {
it('should return an equivalent observable', (done) => {
const val = 5;
observe(Promise.resolve(val)).subscribe((res) => {
expect(res).toEqual(val);
done();
});
});
});

describe('when the passed value is neither a promise nor an observable', () => {
it('should return an observable that emits the passed value', (done) => {
const val = 5;
observe(val).subscribe((res) => {
expect(res).toEqual(val);
done();
});
});
});
});
15 changes: 15 additions & 0 deletions libs/core/src/utils/observe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import {
Observable,
isObservable,
from,
} from 'rxjs';

/**
* Converts a value to an observable.
* If the value is an observable, just returns that observable.
* If the value is a promise, converts it to an observable (see rxjs `from`).
* If the value is neither, just returns an observable that immediately emits the value.
*/
export function observe<T>(val: T | Promise<T> | Observable<T>): Observable<T> {
return isObservable(val) ? val : from(Promise.resolve(val));
}
1 change: 1 addition & 0 deletions libs/core/src/utils/public_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ export { shuffle } from './shuffle';
export { unique } from './unique';
export * from './long-arithmetic';
export * from './identity';
export * from './observe';

0 comments on commit 1874709

Please sign in to comment.