简体   繁体   中英

Observable from rxjs

According to this topic: What is the difference between Promises and Observables?

It was said there by many users that Observable is like a stream. It is really hard to me to understand, how particular endpoint for example this one:

https://jsonplaceholder.typicode.com/posts

can returns many values over time. Since it is http request a single resposne is returned no matter if it was succeed or failed.

You are correct, an http request will still only return a single event when using it with observables. So if the only asyncronous operation you are doing is a single http request, there is no benefit from using an observable over a promise.

The power of RxJS and observables comes when you start combining several observable streams together. This can be done with operators like mergeMap, switchMap, forkJoin, combineLatest, etc. When you start doing this you can get a lot of benefits from having your http requests as observables.

Take polling for example, creating an event stream that fires every 10 seconds and then polls the server with an http request is a use case where doing http requests with observables really shines.

Observables are useful when we want to manage and/or combine multiple events over time.

Lets imagine we have a method will return a promise for that JSON:

const dataPromise = fetchData('https://jsonplaceholder.typicode.com/posts');

Also, imagine that we're tracking user presence on the current page:

const userLeavePromise = trackUserPresence();

Lets now draw timelines for the data fetching and user leaving events. Here o stands for event, happening in time:

            1s  2s  3s  4s  5s
data        ------------o
userLeave   --------o

For example sake, data would be fetched at 4th second, while our restless user would leave the page at 3rd. In this case we want to cancel the fetch operation and all post-processing callbacks (in Promise terms, all .then -ned functions).

For such (and many more) situations RxJS provides lots of operators that let us combine events over time.

In this particular case we would take data, Until user leaves the page:

// Observable for data
const data$ = fetchData('https://jsonplaceholder.typicode.com/posts');

// Observable for user leave
const userLeave$ = trackUserPresence();

data$
  .takeUntil(userLeave$)
  .subscribe(data => console.log(data))

Comparing http request by a promise and observable is not much different because the observable completes once the request is done so it is not a long lived observable. But the one below emits each time you click the button.

 const { fromEvent } = rxjs; fromEvent(document.getElementById('clickMe'), 'click').subscribe(() => { console.log('clicked button'); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script> <button id="clickMe">Click me</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM