0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
ConductedClever
  • 4,175
  • 2
  • 35
  • 69

1 Answers1

1

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 the asyncScheduler, like this:

observable.pipe(
    observeOn(asyncScheduler)
).subscribe(
    ...
)

Here is a demo: https://stackblitz.com/edit/rxjs-ahglez

ggradnig
  • 13,119
  • 2
  • 37
  • 61
  • Very excelent answer. Although a complete list of possible solutions and comparison between them will be also good. Thanks. – ConductedClever Dec 15 '18 at 08:39
  • Oops! Some problems. I have tested that on console.log and then on UI. on console.log every thing goes right on your solution, but on UI changes, setTimeout does not block UI but yours do. Anything to add? – ConductedClever Dec 15 '18 at 09:08