Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(core): add observe util #2808

Merged
merged 1 commit into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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';
Loading