-
-
Notifications
You must be signed in to change notification settings - Fork 28
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(core): add
observe
util (#2808)
- Loading branch information
Showing
3 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
}); | ||
}); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters