1.Synchronous observable:
Observables are lazy Push collections of multiple values.
In our async operator we've used setTimeout
, this setTimeout
will assure that the main thread will not get blocked because setTimeout
is a browser API and our code will be moved to the event loop.
const simpleBlockingOperator =
(noOfLoops: number) =>
<T>(source: Observable<T>): Observable<T> => {
return new Observable((observable) => {
source.subscribe({
next: (no) => {
let loops = 0;
while (loops !== noOfLoops) {
loops++;
}
console.log("Done loooping" + loops, " ", noOfLoops);
return observable.next(no);
},
error: (error) => observable.error(error),
complete: () => observable.complete(),
});
});
};
2.Asynchronous observable:
const simpleNonBlockingOperator =
(noOfLoops: number) =>
<T>(source: Observable<T>): Observable<T> => {
return new Observable((observable) => {
source.subscribe({
next: (no) => {
setTimeout(() => {
let loops = 0;
while (loops !== noOfLoops) {
loops++;
}
console.log("Done loooping" + loops, " ", noOfLoops);
return observable.next(no);
}, 0);
},
error: (error) => observable.error(error),
complete: () => observable.complete(),
});
});
};
No comments:
Post a Comment