jhon.smith
jhon.smith

Reputation: 2043

confused about rxjs observables

I am reading a piece of code

import { Observable } from 'rxjs/Observable';

// PROMISE
const myPromise = new Promise((resolve) => {
  console.log('Hello from Promise');
  resolve(1);
});
myPromise.then(o => console.log(o));
myPromise.then(o => console.log(o));

// OBSERVABLE
const myObservable = Observable.create((observer) => {
  console.log('Hello from Observable');
  observer.next(1);
  observer.next(2);
  observer.next(3);
});
myObservable.subscribe(o => console.log(o));
myObservable.subscribe(o => console.log(o));

The output from the above code is

Hello from Promise
Hello from Observable
1
2
3
Hello from Observable
1
2
3
1
1

I understand everything except for the last two 1 1 in the output from where did the last two 1,1 popup ?

The source code is from this article

https://codeburst.io/rxjs-by-example-part-2-8c6eda15bd7f

Kindly help.

Upvotes: 1

Views: 61

Answers (1)

Fan Cheung
Fan Cheung

Reputation: 11380

the last 1 1 is from the promise

myPromise.then(o => console.log(o));
myPromise.then(o => console.log(o));

since your observable is a sync function, but the promise resolve is async that's why it get called at last.

Upvotes: 1

Related Questions