skip to Main Content

I’m surprised by the order of the output of this Observable example:

<script type="module">


import { of } from 'https://dev.jspm.io/rxjs@6';

console.log("1. before subscribe");
of(["asd"]).subscribe(paramMap => {
    console.log("2. in subscribe");
});
console.log("3. after subscribe");


</script>

This produces this output:

1. before subscribe
2. in subscribe
3. after subscribe

How is this output possible? Shouldn’t Observables be asynchronous, and the log in subscribe happen last?

2

Answers


  1. This is as documented in the RxJs documentation:

    Remember that callbacks provided to subscribe are not guaranteed to be called asynchronously. It is an Observable itself that decides when these functions will be called. For example of by default emits all its values synchronously. Always check documentation for how given Observable will behave when subscribed and if its default behavior can be modified with a scheduler.

    And in particular, the documentation for of:

    An Observable that synchronously emits the arguments…

    Login or Signup to reply.
  2. As mentioned the default for of is sync,

    But you can pass an asyncScheduler to make it async

    eg.

    <script type="module">
    import { of,  asyncScheduler } from 'https://dev.jspm.io/rxjs@6';
    
    console.log("1. before subscribe");
    of(["asd"],  asyncScheduler)
      .subscribe(paramMap => {
        console.log("2. in subscribe");
      });
    console.log("3. after subscribe");
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search