I want to let RxJS Observable to handle my heavy job. But I want it make the subscription async if needed. For example:
const observable = Rx.Observable.create(function (observer) {
observer.next(1);
var cycle = 100;
while(cycle-- > 0){
observer.next(2);
}
observer.next(3);
observer.complete();
});
console.log('before');
observable.subscribe({
next: x => console.log('got value ' + x),
error: err => console.error('something wrong occurred: ' + err),
complete: () => console.log('done'),
});
console.log('after');
in this case, the after string gets printed after whole data out from observable. But I want observable to handle the heavy job and when needed, make the remaining of job async.
So one way that gets to my mind, is to put the heavy part in an setTimeout. I have searched the web but no solution achieved yet. What are the possible ways and which one is better?
Instead of using
setTimeout
, it's better to use the built-in RxJS scheduling mechanisms. For example, to make your subscription async, you can schedule it with theasyncScheduler
, like this:Here is a demo: https://stackblitz.com/edit/rxjs-ahglez