Last active
November 21, 2019 18:57
-
-
Save traviskaufman/1534062cbfea499099e101a05175b3e0 to your computer and use it in GitHub Desktop.
Demystifying RxJS, Part I: from()
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
function from<T>(convertible: Promise<T> | ArrayLike<T>): Observable<T> { | |
if (typeof (convertible as any).length === "number") { | |
const arrayLike = convertible as ArrayLike<T>; | |
return new Observable(obs => { | |
for (let i = 0; i < arrayLike.length; i++) { | |
obs.next(arrayLike[i]); | |
} | |
obs.complete(); | |
}); | |
} | |
// Otherwise, it's a promise | |
const promise = convertible as Promise<T>; | |
return new Observable(obs => { | |
promise | |
.then(x => { | |
obs.next(x); | |
obs.complete(); | |
}) | |
.catch(err => obs.error(err)); | |
}); | |
} | |
// Logs: | |
// fromArray: 4 | |
// fromArray: 5 | |
// fromArray: 6 | |
from([4, 5, 6]).subscribe(x => console.log("fromArray:", x)); | |
// Waits 1.1 seconds, then logs: | |
// fromPromise: 42 | |
from(new Promise(resolve => setTimeout(() => resolve(42), 1100))).subscribe( | |
x => { | |
console.log("fromPromise:", x); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment