JavaScript Promise и RxJS Observable
Основные различия между Promise и Observable
Обещание против наблюдаемого
Нетерпеливый против ленивого
Promise
нетерпелив, а Observable
ленив. Это демо.
const hello = new Promise((resolve, reject) => { console.log('Eager. I am insider. Hello!'); resolve('Hi! Nice to meet you.'); }); console.log('Before calling "then" method on Promise'); hello.then(res => console.log(`Hallo! I'm from Promise. ${res}`));
Советы. Вы можете запустить этот код прямо в консоли браузера Chrome (сочетание клавиш в macOS: Opt + Command + I. Откройте вкладку «Консоль», скопируйте выше сегмент кода и нажмите Enter)
const { Observable } = rxjs; const hello$ = new Observable(observer => { console.log('Lazy. I am insider. Hello!'); observer.next('Hi! Nice to meet you.'); observer.complete(); }); console.log('Before calling "subscribe" on Observable'); hello$.subscribe({ next: console.log, complete: () => console.log('Goodbye') });
Советы. Вы можете открыть новую вкладку на https://rxjs-dev.firebaseapp.com/, прежде чем открывать консоль Chrome для запуска этого кода. (импортированная библиотека rxjs)
Наблюдаемый может быть синхронным
Promise
всегда асинхронно.
const hello = new Promise((resolve, reject) => { resolve('Hi! Nice to meet you.'); }); console.log('Before calling "then" method on Promise'); hello.then(res => console.log(`Hallo! I'm from Promise. ${res}`)); console.log('After calling then on Promise (proff of being always async');
Observable
может быть синхронным или асинхронным
const { Observable } = rxjs; const greetingLady$ = new Observable(observer => { observer.next('Hello! I am glad to get to know you.'); observer.complete(); }); console.log('Before calling subscrible on Observable'); greetingLady$.subscribe({ next: console.log, complete: () => console.log('End of conversation with preety lady') }); console.log('After calling subscribe on Observable (proof of being able to execute sync');
const tiredGreetingLady2$ = new Observable(observer => { setTimeout(() => { observer.next('Hello! I am glad to get to know you.'); observer.complete(); }, 2000); }); console.log('Before calling subscribe on Observable'); tiredGreetingLady2$.subscribe({ next: console.log, complete: () => console.log('End of conversation with tired preety lady') }); console.log('After calling subscribe on Observable (proof of being able to execute async)');
Observable может выдавать несколько значений
объект Promise может предоставить только одно значение. Это может быть массив, но это все равно один объект. Напротив, Observable может выдавать несколько значений с течением времени.
const { Observable } = rxjs; const notifications$ = new Observable(observer => { const interval = setInterval(() => { observer.next('New notification'); }, 2000); return () => clearInterval(interval); }); const subscription = notifications$.subscribe(console.log); setTimeout(() => subscription.unsubscribe(), 8000);
Операторы рулят!
Вы можете применить операторы RxJS к Observable, чтобы получить новый адаптированный поток. RxJS наиболее интересен с большим количеством операторов, которые можно применить к Observables, чтобы получить новый адаптированный поток.
const { Observable } = rxjs; const { map } = rxjs.operators; const notifications$ = new Observable(observer => { const interval = setInterval(() => { observer.next('New notification'); }, 2000); return () => clearInterval(interval); }); const enhancedNotifications$ = notifications$.pipe( map(message => `${message} ${new Date()}`) ); const subscription = enhancedNotifications$.subscribe(console.log); setTimeout(() => subscription.unsubscribe(), 8000);
См.: https://medium.com/javascript-everyday/javascript-theory-promise-vs-observable-d3087bc1239a