From 187470977cfef9791e667b00d1a7ccff140f635e Mon Sep 17 00:00:00 2001 From: griest024 Date: Wed, 22 May 2024 18:08:17 -0400 Subject: [PATCH] feat(core): add `observe` util (#2808) --- libs/core/src/utils/observe.spec.ts | 35 +++++++++++++++++++++++++++++ libs/core/src/utils/observe.ts | 15 +++++++++++++ libs/core/src/utils/public_api.ts | 1 + 3 files changed, 51 insertions(+) create mode 100644 libs/core/src/utils/observe.spec.ts create mode 100644 libs/core/src/utils/observe.ts diff --git a/libs/core/src/utils/observe.spec.ts b/libs/core/src/utils/observe.spec.ts new file mode 100644 index 0000000000..97b76d99d9 --- /dev/null +++ b/libs/core/src/utils/observe.spec.ts @@ -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(); + }); + }); + }); +}); diff --git a/libs/core/src/utils/observe.ts b/libs/core/src/utils/observe.ts new file mode 100644 index 0000000000..be585eb008 --- /dev/null +++ b/libs/core/src/utils/observe.ts @@ -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(val: T | Promise | Observable): Observable { + return isObservable(val) ? val : from(Promise.resolve(val)); +} diff --git a/libs/core/src/utils/public_api.ts b/libs/core/src/utils/public_api.ts index 20d8f96dcd..d5e368d77e 100644 --- a/libs/core/src/utils/public_api.ts +++ b/libs/core/src/utils/public_api.ts @@ -13,3 +13,4 @@ export { shuffle } from './shuffle'; export { unique } from './unique'; export * from './long-arithmetic'; export * from './identity'; +export * from './observe';